message_queue.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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, CoreStringNames::get_singleton()->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::_transfer_messages_to_main_queue() {
  184. if (pages.size() == 0) {
  185. return OK;
  186. }
  187. CallQueue *mq = MessageQueue::main_singleton;
  188. DEV_ASSERT(!mq->allocator_is_custom && !allocator_is_custom); // Transferring pages is only safe if using the same alloator parameters.
  189. mq->mutex.lock();
  190. // Here we're transferring the data from this queue to the main one.
  191. // However, it's very unlikely big amounts of messages will be queued here,
  192. // so PagedArray/Pool would be overkill. Also, in most cases the data will fit
  193. // an already existing page of the main queue.
  194. // Let's see if our first (likely only) page fits the current target queue page.
  195. uint32_t src_page = 0;
  196. {
  197. if (mq->pages_used) {
  198. uint32_t dst_page = mq->pages_used - 1;
  199. uint32_t dst_offset = mq->page_bytes[dst_page];
  200. if (dst_offset + page_bytes[0] < uint32_t(PAGE_SIZE_BYTES)) {
  201. memcpy(mq->pages[dst_page]->data + dst_offset, pages[0]->data, page_bytes[0]);
  202. mq->page_bytes[dst_page] += page_bytes[0];
  203. src_page++;
  204. }
  205. }
  206. }
  207. // Any other possibly existing source page needs to be added.
  208. if (mq->pages_used + (pages_used - src_page) > mq->max_pages) {
  209. fprintf(stderr, "Failed appending thread queue. Message queue out of memory. %s\n", mq->error_text.utf8().get_data());
  210. mq->statistics();
  211. mq->mutex.unlock();
  212. return ERR_OUT_OF_MEMORY;
  213. }
  214. for (; src_page < pages_used; src_page++) {
  215. mq->_add_page();
  216. memcpy(mq->pages[mq->pages_used - 1]->data, pages[src_page]->data, page_bytes[src_page]);
  217. mq->page_bytes[mq->pages_used - 1] = page_bytes[src_page];
  218. }
  219. mq->mutex.unlock();
  220. page_bytes[0] = 0;
  221. pages_used = 1;
  222. return OK;
  223. }
  224. Error CallQueue::flush() {
  225. // Thread overrides are not meant to be flushed, but appended to the main one.
  226. if (unlikely(this == MessageQueue::thread_singleton)) {
  227. return _transfer_messages_to_main_queue();
  228. }
  229. LOCK_MUTEX;
  230. if (pages.size() == 0) {
  231. // Never allocated
  232. UNLOCK_MUTEX;
  233. return OK; // Do nothing.
  234. }
  235. if (flushing) {
  236. UNLOCK_MUTEX;
  237. return ERR_BUSY;
  238. }
  239. flushing = true;
  240. uint32_t i = 0;
  241. uint32_t offset = 0;
  242. while (i < pages_used && offset < page_bytes[i]) {
  243. Page *page = pages[i];
  244. //lock on each iteration, so a call can re-add itself to the message queue
  245. Message *message = (Message *)&page->data[offset];
  246. uint32_t advance = sizeof(Message);
  247. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  248. advance += sizeof(Variant) * message->args;
  249. }
  250. //pre-advance so this function is reentrant
  251. offset += advance;
  252. Object *target = message->callable.get_object();
  253. UNLOCK_MUTEX;
  254. switch (message->type & FLAG_MASK) {
  255. case TYPE_CALL: {
  256. if (target || (message->type & FLAG_NULL_IS_OK)) {
  257. Variant *args = (Variant *)(message + 1);
  258. _call_function(message->callable, args, message->args, message->type & FLAG_SHOW_ERROR);
  259. }
  260. } break;
  261. case TYPE_NOTIFICATION: {
  262. if (target) {
  263. target->notification(message->notification);
  264. }
  265. } break;
  266. case TYPE_SET: {
  267. if (target) {
  268. Variant *arg = (Variant *)(message + 1);
  269. target->set(message->callable.get_method(), *arg);
  270. }
  271. } break;
  272. }
  273. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  274. Variant *args = (Variant *)(message + 1);
  275. for (int k = 0; k < message->args; k++) {
  276. args[k].~Variant();
  277. }
  278. }
  279. message->~Message();
  280. LOCK_MUTEX;
  281. if (offset == page_bytes[i]) {
  282. i++;
  283. offset = 0;
  284. }
  285. }
  286. page_bytes[0] = 0;
  287. pages_used = 1;
  288. flushing = false;
  289. UNLOCK_MUTEX;
  290. return OK;
  291. }
  292. void CallQueue::clear() {
  293. LOCK_MUTEX;
  294. if (pages.size() == 0) {
  295. UNLOCK_MUTEX;
  296. return; // Nothing to clear.
  297. }
  298. for (uint32_t i = 0; i < pages_used; i++) {
  299. uint32_t offset = 0;
  300. while (offset < page_bytes[i]) {
  301. Page *page = pages[i];
  302. //lock on each iteration, so a call can re-add itself to the message queue
  303. Message *message = (Message *)&page->data[offset];
  304. uint32_t advance = sizeof(Message);
  305. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  306. advance += sizeof(Variant) * message->args;
  307. }
  308. offset += advance;
  309. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  310. Variant *args = (Variant *)(message + 1);
  311. for (int k = 0; k < message->args; k++) {
  312. args[k].~Variant();
  313. }
  314. }
  315. message->~Message();
  316. }
  317. }
  318. pages_used = 1;
  319. page_bytes[0] = 0;
  320. UNLOCK_MUTEX;
  321. }
  322. void CallQueue::statistics() {
  323. LOCK_MUTEX;
  324. HashMap<StringName, int> set_count;
  325. HashMap<int, int> notify_count;
  326. HashMap<Callable, int> call_count;
  327. int null_count = 0;
  328. for (uint32_t i = 0; i < pages_used; i++) {
  329. uint32_t offset = 0;
  330. while (offset < page_bytes[i]) {
  331. Page *page = pages[i];
  332. //lock on each iteration, so a call can re-add itself to the message queue
  333. Message *message = (Message *)&page->data[offset];
  334. uint32_t advance = sizeof(Message);
  335. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  336. advance += sizeof(Variant) * message->args;
  337. }
  338. Object *target = message->callable.get_object();
  339. bool null_target = true;
  340. switch (message->type & FLAG_MASK) {
  341. case TYPE_CALL: {
  342. if (target || (message->type & FLAG_NULL_IS_OK)) {
  343. if (!call_count.has(message->callable)) {
  344. call_count[message->callable] = 0;
  345. }
  346. call_count[message->callable]++;
  347. null_target = false;
  348. }
  349. } break;
  350. case TYPE_NOTIFICATION: {
  351. if (target) {
  352. if (!notify_count.has(message->notification)) {
  353. notify_count[message->notification] = 0;
  354. }
  355. notify_count[message->notification]++;
  356. null_target = false;
  357. }
  358. } break;
  359. case TYPE_SET: {
  360. if (target) {
  361. StringName t = message->callable.get_method();
  362. if (!set_count.has(t)) {
  363. set_count[t] = 0;
  364. }
  365. set_count[t]++;
  366. null_target = false;
  367. }
  368. } break;
  369. }
  370. if (null_target) {
  371. // Object was deleted.
  372. fprintf(stdout, "Object was deleted while awaiting a callback.\n");
  373. null_count++;
  374. }
  375. offset += advance;
  376. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  377. Variant *args = (Variant *)(message + 1);
  378. for (int k = 0; k < message->args; k++) {
  379. args[k].~Variant();
  380. }
  381. }
  382. message->~Message();
  383. }
  384. }
  385. fprintf(stdout, "TOTAL PAGES: %d (%d bytes).\n", pages_used, pages_used * PAGE_SIZE_BYTES);
  386. fprintf(stdout, "NULL count: %d.\n", null_count);
  387. for (const KeyValue<StringName, int> &E : set_count) {
  388. fprintf(stdout, "SET %s: %d.\n", String(E.key).utf8().get_data(), E.value);
  389. }
  390. for (const KeyValue<Callable, int> &E : call_count) {
  391. fprintf(stdout, "CALL %s: %d.\n", String(E.key).utf8().get_data(), E.value);
  392. }
  393. for (const KeyValue<int, int> &E : notify_count) {
  394. fprintf(stdout, "NOTIFY %d: %d.\n", E.key, E.value);
  395. }
  396. UNLOCK_MUTEX;
  397. }
  398. bool CallQueue::is_flushing() const {
  399. return flushing;
  400. }
  401. bool CallQueue::has_messages() const {
  402. if (pages_used == 0) {
  403. return false;
  404. }
  405. if (pages_used == 1 && page_bytes[0] == 0) {
  406. return false;
  407. }
  408. return true;
  409. }
  410. int CallQueue::get_max_buffer_usage() const {
  411. return pages.size() * PAGE_SIZE_BYTES;
  412. }
  413. CallQueue::CallQueue(Allocator *p_custom_allocator, uint32_t p_max_pages, const String &p_error_text) {
  414. if (p_custom_allocator) {
  415. allocator = p_custom_allocator;
  416. allocator_is_custom = true;
  417. } else {
  418. allocator = memnew(Allocator(16)); // 16 elements per allocator page, 64kb per allocator page. Anything small will do, though.
  419. allocator_is_custom = false;
  420. }
  421. max_pages = p_max_pages;
  422. error_text = p_error_text;
  423. }
  424. CallQueue::~CallQueue() {
  425. clear();
  426. // Let go of pages.
  427. for (uint32_t i = 0; i < pages.size(); i++) {
  428. allocator->free(pages[i]);
  429. }
  430. if (!allocator_is_custom) {
  431. memdelete(allocator);
  432. }
  433. // This is done here to avoid a circular dependency between the safety checks and the thread singleton pointer.
  434. if (this == MessageQueue::thread_singleton) {
  435. MessageQueue::thread_singleton = nullptr;
  436. }
  437. }
  438. //////////////////////
  439. CallQueue *MessageQueue::main_singleton = nullptr;
  440. thread_local CallQueue *MessageQueue::thread_singleton = nullptr;
  441. void MessageQueue::set_thread_singleton_override(CallQueue *p_thread_singleton) {
  442. DEV_ASSERT(p_thread_singleton); // To unset the thread singleton, don't call this with nullptr, but just memfree() it.
  443. #ifdef DEV_ENABLED
  444. if (thread_singleton) {
  445. thread_singleton->is_current_thread_override = false;
  446. }
  447. #endif
  448. thread_singleton = p_thread_singleton;
  449. #ifdef DEV_ENABLED
  450. if (thread_singleton) {
  451. thread_singleton->is_current_thread_override = true;
  452. }
  453. #endif
  454. }
  455. MessageQueue::MessageQueue() :
  456. CallQueue(nullptr,
  457. 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,
  458. "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.") {
  459. ERR_FAIL_COND_MSG(main_singleton != nullptr, "A MessageQueue singleton already exists.");
  460. main_singleton = this;
  461. }
  462. MessageQueue::~MessageQueue() {
  463. main_singleton = nullptr;
  464. }