message_queue.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /**************************************************************************/
  2. /* message_queue.cpp */
  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. #include "message_queue.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/core_string_names.h"
  33. #include "core/object/class_db.h"
  34. #include "core/object/script_language.h"
  35. #include <stdio.h>
  36. #ifdef DEV_ENABLED
  37. // Includes safety checks to ensure that a queue set as a thread singleton override
  38. // is only ever called from the thread it was set for.
  39. #define LOCK_MUTEX \
  40. if (this != MessageQueue::thread_singleton) { \
  41. DEV_ASSERT(!is_current_thread_override); \
  42. mutex.lock(); \
  43. } else { \
  44. DEV_ASSERT(is_current_thread_override); \
  45. }
  46. #else
  47. #define LOCK_MUTEX \
  48. if (this != MessageQueue::thread_singleton) { \
  49. mutex.lock(); \
  50. }
  51. #endif
  52. #define UNLOCK_MUTEX \
  53. if (this != MessageQueue::thread_singleton) { \
  54. mutex.unlock(); \
  55. }
  56. void CallQueue::_add_page() {
  57. if (pages_used == page_bytes.size()) {
  58. pages.push_back(allocator->alloc());
  59. page_bytes.push_back(0);
  60. }
  61. page_bytes[pages_used] = 0;
  62. pages_used++;
  63. }
  64. Error CallQueue::push_callp(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  65. return push_callablep(Callable(p_id, p_method), p_args, p_argcount, p_show_error);
  66. }
  67. Error CallQueue::push_callp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  68. return push_callp(p_object->get_instance_id(), p_method, p_args, p_argcount, p_show_error);
  69. }
  70. Error CallQueue::push_notification(Object *p_object, int p_notification) {
  71. return push_notification(p_object->get_instance_id(), p_notification);
  72. }
  73. Error CallQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
  74. return push_set(p_object->get_instance_id(), p_prop, p_value);
  75. }
  76. Error CallQueue::push_callablep(const Callable &p_callable, const Variant **p_args, int p_argcount, bool p_show_error) {
  77. uint32_t room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
  78. ERR_FAIL_COND_V_MSG(room_needed > uint32_t(PAGE_SIZE_BYTES), ERR_INVALID_PARAMETER, "Message is too large to fit on a page (" + itos(PAGE_SIZE_BYTES) + " bytes), consider passing less arguments.");
  79. LOCK_MUTEX;
  80. _ensure_first_page();
  81. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  82. if (pages_used == max_pages) {
  83. fprintf(stderr, "Failed method: %s. Message queue out of memory. %s\n", String(p_callable).utf8().get_data(), error_text.utf8().get_data());
  84. statistics();
  85. UNLOCK_MUTEX;
  86. return ERR_OUT_OF_MEMORY;
  87. }
  88. _add_page();
  89. }
  90. Page *page = pages[pages_used - 1];
  91. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  92. Message *msg = memnew_placement(buffer_end, Message);
  93. msg->args = p_argcount;
  94. msg->callable = p_callable;
  95. msg->type = TYPE_CALL;
  96. if (p_show_error) {
  97. msg->type |= FLAG_SHOW_ERROR;
  98. }
  99. // Support callables of static methods.
  100. if (p_callable.get_object_id().is_null() && p_callable.is_valid()) {
  101. msg->type |= FLAG_NULL_IS_OK;
  102. }
  103. buffer_end += sizeof(Message);
  104. for (int i = 0; i < p_argcount; i++) {
  105. Variant *v = memnew_placement(buffer_end, Variant);
  106. buffer_end += sizeof(Variant);
  107. *v = *p_args[i];
  108. }
  109. page_bytes[pages_used - 1] += room_needed;
  110. UNLOCK_MUTEX;
  111. return OK;
  112. }
  113. Error CallQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
  114. LOCK_MUTEX;
  115. uint32_t room_needed = sizeof(Message) + sizeof(Variant);
  116. _ensure_first_page();
  117. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  118. if (pages_used == max_pages) {
  119. String type;
  120. if (ObjectDB::get_instance(p_id)) {
  121. type = ObjectDB::get_instance(p_id)->get_class();
  122. }
  123. fprintf(stderr, "Failed set: %s: %s target ID: %s. Message queue out of memory. %s\n", type.utf8().get_data(), String(p_prop).utf8().get_data(), itos(p_id).utf8().get_data(), error_text.utf8().get_data());
  124. statistics();
  125. UNLOCK_MUTEX;
  126. return ERR_OUT_OF_MEMORY;
  127. }
  128. _add_page();
  129. }
  130. Page *page = pages[pages_used - 1];
  131. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  132. Message *msg = memnew_placement(buffer_end, Message);
  133. msg->args = 1;
  134. msg->callable = Callable(p_id, p_prop);
  135. msg->type = TYPE_SET;
  136. buffer_end += sizeof(Message);
  137. Variant *v = memnew_placement(buffer_end, Variant);
  138. *v = p_value;
  139. page_bytes[pages_used - 1] += room_needed;
  140. UNLOCK_MUTEX;
  141. return OK;
  142. }
  143. Error CallQueue::push_notification(ObjectID p_id, int p_notification) {
  144. ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
  145. LOCK_MUTEX;
  146. uint32_t room_needed = sizeof(Message);
  147. _ensure_first_page();
  148. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  149. if (pages_used == max_pages) {
  150. fprintf(stderr, "Failed notification: %d target ID: %s. Message queue out of memory. %s\n", p_notification, itos(p_id).utf8().get_data(), error_text.utf8().get_data());
  151. statistics();
  152. UNLOCK_MUTEX;
  153. return ERR_OUT_OF_MEMORY;
  154. }
  155. _add_page();
  156. }
  157. Page *page = pages[pages_used - 1];
  158. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  159. Message *msg = memnew_placement(buffer_end, Message);
  160. msg->type = TYPE_NOTIFICATION;
  161. msg->callable = Callable(p_id, CoreStringName(notification)); //name is meaningless but callable needs it
  162. //msg->target;
  163. msg->notification = p_notification;
  164. page_bytes[pages_used - 1] += room_needed;
  165. UNLOCK_MUTEX;
  166. return OK;
  167. }
  168. void CallQueue::_call_function(const Callable &p_callable, const Variant *p_args, int p_argcount, bool p_show_error) {
  169. const Variant **argptrs = nullptr;
  170. if (p_argcount) {
  171. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
  172. for (int i = 0; i < p_argcount; i++) {
  173. argptrs[i] = &p_args[i];
  174. }
  175. }
  176. Callable::CallError ce;
  177. Variant ret;
  178. p_callable.callp(argptrs, p_argcount, ret, ce);
  179. if (p_show_error && ce.error != Callable::CallError::CALL_OK) {
  180. ERR_PRINT("Error calling deferred method: " + Variant::get_callable_error_text(p_callable, argptrs, p_argcount, ce) + ".");
  181. }
  182. }
  183. Error CallQueue::flush() {
  184. LOCK_MUTEX;
  185. if (pages.size() == 0) {
  186. // Never allocated
  187. UNLOCK_MUTEX;
  188. return OK; // Do nothing.
  189. }
  190. if (flushing) {
  191. UNLOCK_MUTEX;
  192. return ERR_BUSY;
  193. }
  194. flushing = true;
  195. uint32_t i = 0;
  196. uint32_t offset = 0;
  197. while (i < pages_used && offset < page_bytes[i]) {
  198. Page *page = pages[i];
  199. //lock on each iteration, so a call can re-add itself to the message queue
  200. Message *message = (Message *)&page->data[offset];
  201. uint32_t advance = sizeof(Message);
  202. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  203. advance += sizeof(Variant) * message->args;
  204. }
  205. //pre-advance so this function is reentrant
  206. offset += advance;
  207. Object *target = message->callable.get_object();
  208. UNLOCK_MUTEX;
  209. switch (message->type & FLAG_MASK) {
  210. case TYPE_CALL: {
  211. if (target || (message->type & FLAG_NULL_IS_OK)) {
  212. Variant *args = (Variant *)(message + 1);
  213. _call_function(message->callable, args, message->args, message->type & FLAG_SHOW_ERROR);
  214. }
  215. } break;
  216. case TYPE_NOTIFICATION: {
  217. if (target) {
  218. target->notification(message->notification);
  219. }
  220. } break;
  221. case TYPE_SET: {
  222. if (target) {
  223. Variant *arg = (Variant *)(message + 1);
  224. target->set(message->callable.get_method(), *arg);
  225. }
  226. } break;
  227. }
  228. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  229. Variant *args = (Variant *)(message + 1);
  230. for (int k = 0; k < message->args; k++) {
  231. args[k].~Variant();
  232. }
  233. }
  234. message->~Message();
  235. LOCK_MUTEX;
  236. if (offset == page_bytes[i]) {
  237. i++;
  238. offset = 0;
  239. }
  240. }
  241. page_bytes[0] = 0;
  242. pages_used = 1;
  243. flushing = false;
  244. UNLOCK_MUTEX;
  245. return OK;
  246. }
  247. void CallQueue::clear() {
  248. LOCK_MUTEX;
  249. if (pages.size() == 0) {
  250. UNLOCK_MUTEX;
  251. return; // Nothing to clear.
  252. }
  253. for (uint32_t i = 0; i < pages_used; i++) {
  254. uint32_t offset = 0;
  255. while (offset < page_bytes[i]) {
  256. Page *page = pages[i];
  257. //lock on each iteration, so a call can re-add itself to the message queue
  258. Message *message = (Message *)&page->data[offset];
  259. uint32_t advance = sizeof(Message);
  260. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  261. advance += sizeof(Variant) * message->args;
  262. }
  263. offset += advance;
  264. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  265. Variant *args = (Variant *)(message + 1);
  266. for (int k = 0; k < message->args; k++) {
  267. args[k].~Variant();
  268. }
  269. }
  270. message->~Message();
  271. }
  272. }
  273. pages_used = 1;
  274. page_bytes[0] = 0;
  275. UNLOCK_MUTEX;
  276. }
  277. void CallQueue::statistics() {
  278. LOCK_MUTEX;
  279. HashMap<StringName, int> set_count;
  280. HashMap<int, int> notify_count;
  281. HashMap<Callable, int> call_count;
  282. int null_count = 0;
  283. for (uint32_t i = 0; i < pages_used; i++) {
  284. uint32_t offset = 0;
  285. while (offset < page_bytes[i]) {
  286. Page *page = pages[i];
  287. //lock on each iteration, so a call can re-add itself to the message queue
  288. Message *message = (Message *)&page->data[offset];
  289. uint32_t advance = sizeof(Message);
  290. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  291. advance += sizeof(Variant) * message->args;
  292. }
  293. Object *target = message->callable.get_object();
  294. bool null_target = true;
  295. switch (message->type & FLAG_MASK) {
  296. case TYPE_CALL: {
  297. if (target || (message->type & FLAG_NULL_IS_OK)) {
  298. if (!call_count.has(message->callable)) {
  299. call_count[message->callable] = 0;
  300. }
  301. call_count[message->callable]++;
  302. null_target = false;
  303. }
  304. } break;
  305. case TYPE_NOTIFICATION: {
  306. if (target) {
  307. if (!notify_count.has(message->notification)) {
  308. notify_count[message->notification] = 0;
  309. }
  310. notify_count[message->notification]++;
  311. null_target = false;
  312. }
  313. } break;
  314. case TYPE_SET: {
  315. if (target) {
  316. StringName t = message->callable.get_method();
  317. if (!set_count.has(t)) {
  318. set_count[t] = 0;
  319. }
  320. set_count[t]++;
  321. null_target = false;
  322. }
  323. } break;
  324. }
  325. if (null_target) {
  326. // Object was deleted.
  327. fprintf(stdout, "Object was deleted while awaiting a callback.\n");
  328. null_count++;
  329. }
  330. offset += advance;
  331. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  332. Variant *args = (Variant *)(message + 1);
  333. for (int k = 0; k < message->args; k++) {
  334. args[k].~Variant();
  335. }
  336. }
  337. message->~Message();
  338. }
  339. }
  340. fprintf(stdout, "TOTAL PAGES: %d (%d bytes).\n", pages_used, pages_used * PAGE_SIZE_BYTES);
  341. fprintf(stdout, "NULL count: %d.\n", null_count);
  342. for (const KeyValue<StringName, int> &E : set_count) {
  343. fprintf(stdout, "SET %s: %d.\n", String(E.key).utf8().get_data(), E.value);
  344. }
  345. for (const KeyValue<Callable, int> &E : call_count) {
  346. fprintf(stdout, "CALL %s: %d.\n", String(E.key).utf8().get_data(), E.value);
  347. }
  348. for (const KeyValue<int, int> &E : notify_count) {
  349. fprintf(stdout, "NOTIFY %d: %d.\n", E.key, E.value);
  350. }
  351. UNLOCK_MUTEX;
  352. }
  353. bool CallQueue::is_flushing() const {
  354. return flushing;
  355. }
  356. bool CallQueue::has_messages() const {
  357. if (pages_used == 0) {
  358. return false;
  359. }
  360. if (pages_used == 1 && page_bytes[0] == 0) {
  361. return false;
  362. }
  363. return true;
  364. }
  365. int CallQueue::get_max_buffer_usage() const {
  366. return pages.size() * PAGE_SIZE_BYTES;
  367. }
  368. CallQueue::CallQueue(Allocator *p_custom_allocator, uint32_t p_max_pages, const String &p_error_text) {
  369. if (p_custom_allocator) {
  370. allocator = p_custom_allocator;
  371. allocator_is_custom = true;
  372. } else {
  373. allocator = memnew(Allocator(16)); // 16 elements per allocator page, 64kb per allocator page. Anything small will do, though.
  374. allocator_is_custom = false;
  375. }
  376. max_pages = p_max_pages;
  377. error_text = p_error_text;
  378. }
  379. CallQueue::~CallQueue() {
  380. clear();
  381. // Let go of pages.
  382. for (uint32_t i = 0; i < pages.size(); i++) {
  383. allocator->free(pages[i]);
  384. }
  385. if (!allocator_is_custom) {
  386. memdelete(allocator);
  387. }
  388. // This is done here to avoid a circular dependency between the safety checks and the thread singleton pointer.
  389. if (this == MessageQueue::thread_singleton) {
  390. MessageQueue::thread_singleton = nullptr;
  391. }
  392. }
  393. //////////////////////
  394. CallQueue *MessageQueue::main_singleton = nullptr;
  395. thread_local CallQueue *MessageQueue::thread_singleton = nullptr;
  396. void MessageQueue::set_thread_singleton_override(CallQueue *p_thread_singleton) {
  397. DEV_ASSERT(p_thread_singleton); // To unset the thread singleton, don't call this with nullptr, but just memfree() it.
  398. #ifdef DEV_ENABLED
  399. if (thread_singleton) {
  400. thread_singleton->is_current_thread_override = false;
  401. }
  402. #endif
  403. thread_singleton = p_thread_singleton;
  404. #ifdef DEV_ENABLED
  405. if (thread_singleton) {
  406. thread_singleton->is_current_thread_override = true;
  407. }
  408. #endif
  409. }
  410. MessageQueue::MessageQueue() :
  411. CallQueue(nullptr,
  412. int(GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "memory/limits/message_queue/max_size_mb", PROPERTY_HINT_RANGE, "1,512,1,or_greater"), 32)) * 1024 * 1024 / PAGE_SIZE_BYTES,
  413. "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.") {
  414. ERR_FAIL_COND_MSG(main_singleton != nullptr, "A MessageQueue singleton already exists.");
  415. main_singleton = this;
  416. }
  417. MessageQueue::~MessageQueue() {
  418. main_singleton = nullptr;
  419. }