message_queue.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. #ifdef DEBUG_ENABLED
  36. #include "core/config/engine.h"
  37. #endif
  38. #ifdef DEV_ENABLED
  39. // Includes sanity checks to ensure that a queue set as a thread singleton override
  40. // is only ever called from the thread it was set for.
  41. #define LOCK_MUTEX \
  42. if (this != MessageQueue::thread_singleton) { \
  43. DEV_ASSERT(!this->is_current_thread_override); \
  44. mutex.lock(); \
  45. } else { \
  46. DEV_ASSERT(this->is_current_thread_override); \
  47. }
  48. #else
  49. #define LOCK_MUTEX \
  50. if (this != MessageQueue::thread_singleton) { \
  51. mutex.lock(); \
  52. }
  53. #endif
  54. #define UNLOCK_MUTEX \
  55. if (this != MessageQueue::thread_singleton) { \
  56. mutex.unlock(); \
  57. }
  58. void CallQueue::_add_page() {
  59. if (pages_used == page_bytes.size()) {
  60. pages.push_back(allocator->alloc());
  61. page_bytes.push_back(0);
  62. }
  63. page_bytes[pages_used] = 0;
  64. pages_used++;
  65. }
  66. Error CallQueue::push_callp(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  67. return push_callablep(Callable(p_id, p_method), p_args, p_argcount, p_show_error);
  68. }
  69. Error CallQueue::push_callp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  70. return push_callp(p_object->get_instance_id(), p_method, p_args, p_argcount, p_show_error);
  71. }
  72. Error CallQueue::push_notification(Object *p_object, int p_notification) {
  73. return push_notification(p_object->get_instance_id(), p_notification);
  74. }
  75. Error CallQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
  76. return push_set(p_object->get_instance_id(), p_prop, p_value);
  77. }
  78. Error CallQueue::push_callablep(const Callable &p_callable, const Variant **p_args, int p_argcount, bool p_show_error) {
  79. uint32_t room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
  80. 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.");
  81. LOCK_MUTEX;
  82. _ensure_first_page();
  83. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  84. if (pages_used == max_pages) {
  85. ERR_PRINT("Failed method: " + p_callable + ". Message queue out of memory. " + error_text);
  86. statistics();
  87. UNLOCK_MUTEX;
  88. return ERR_OUT_OF_MEMORY;
  89. }
  90. _add_page();
  91. }
  92. Page *page = pages[pages_used - 1];
  93. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  94. Message *msg = memnew_placement(buffer_end, Message);
  95. msg->args = p_argcount;
  96. msg->callable = p_callable;
  97. msg->type = TYPE_CALL;
  98. if (p_show_error) {
  99. msg->type |= FLAG_SHOW_ERROR;
  100. }
  101. // Support callables of static methods.
  102. if (p_callable.get_object_id().is_null() && p_callable.is_valid()) {
  103. msg->type |= FLAG_NULL_IS_OK;
  104. }
  105. buffer_end += sizeof(Message);
  106. for (int i = 0; i < p_argcount; i++) {
  107. Variant *v = memnew_placement(buffer_end, Variant);
  108. buffer_end += sizeof(Variant);
  109. *v = *p_args[i];
  110. }
  111. page_bytes[pages_used - 1] += room_needed;
  112. UNLOCK_MUTEX;
  113. return OK;
  114. }
  115. Error CallQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
  116. LOCK_MUTEX;
  117. uint32_t room_needed = sizeof(Message) + sizeof(Variant);
  118. _ensure_first_page();
  119. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  120. if (pages_used == max_pages) {
  121. String type;
  122. if (ObjectDB::get_instance(p_id)) {
  123. type = ObjectDB::get_instance(p_id)->get_class();
  124. }
  125. ERR_PRINT("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id) + ". Message queue out of memory. " + error_text);
  126. statistics();
  127. UNLOCK_MUTEX;
  128. return ERR_OUT_OF_MEMORY;
  129. }
  130. _add_page();
  131. }
  132. Page *page = pages[pages_used - 1];
  133. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  134. Message *msg = memnew_placement(buffer_end, Message);
  135. msg->args = 1;
  136. msg->callable = Callable(p_id, p_prop);
  137. msg->type = TYPE_SET;
  138. buffer_end += sizeof(Message);
  139. Variant *v = memnew_placement(buffer_end, Variant);
  140. *v = p_value;
  141. page_bytes[pages_used - 1] += room_needed;
  142. UNLOCK_MUTEX;
  143. return OK;
  144. }
  145. Error CallQueue::push_notification(ObjectID p_id, int p_notification) {
  146. ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
  147. LOCK_MUTEX;
  148. uint32_t room_needed = sizeof(Message);
  149. _ensure_first_page();
  150. if ((page_bytes[pages_used - 1] + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  151. if (pages_used == max_pages) {
  152. ERR_PRINT("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id) + ". Message queue out of memory. " + error_text);
  153. statistics();
  154. UNLOCK_MUTEX;
  155. return ERR_OUT_OF_MEMORY;
  156. }
  157. _add_page();
  158. }
  159. Page *page = pages[pages_used - 1];
  160. uint8_t *buffer_end = &page->data[page_bytes[pages_used - 1]];
  161. Message *msg = memnew_placement(buffer_end, Message);
  162. msg->type = TYPE_NOTIFICATION;
  163. msg->callable = Callable(p_id, CoreStringNames::get_singleton()->notification); //name is meaningless but callable needs it
  164. //msg->target;
  165. msg->notification = p_notification;
  166. page_bytes[pages_used - 1] += room_needed;
  167. UNLOCK_MUTEX;
  168. return OK;
  169. }
  170. void CallQueue::_call_function(const Callable &p_callable, const Variant *p_args, int p_argcount, bool p_show_error) {
  171. const Variant **argptrs = nullptr;
  172. if (p_argcount) {
  173. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
  174. for (int i = 0; i < p_argcount; i++) {
  175. argptrs[i] = &p_args[i];
  176. }
  177. }
  178. Callable::CallError ce;
  179. Variant ret;
  180. p_callable.callp(argptrs, p_argcount, ret, ce);
  181. if (p_show_error && ce.error != Callable::CallError::CALL_OK) {
  182. ERR_PRINT("Error calling deferred method: " + Variant::get_callable_error_text(p_callable, argptrs, p_argcount, ce) + ".");
  183. }
  184. }
  185. Error CallQueue::_transfer_messages_to_main_queue() {
  186. if (pages.size() == 0) {
  187. return OK;
  188. }
  189. CallQueue *mq = MessageQueue::main_singleton;
  190. DEV_ASSERT(!mq->allocator_is_custom && !allocator_is_custom); // Transferring pages is only safe if using the same alloator parameters.
  191. mq->mutex.lock();
  192. // Here we're transferring the data from this queue to the main one.
  193. // However, it's very unlikely big amounts of messages will be queued here,
  194. // so PagedArray/Pool would be overkill. Also, in most cases the data will fit
  195. // an already existing page of the main queue.
  196. // Let's see if our first (likely only) page fits the current target queue page.
  197. uint32_t src_page = 0;
  198. {
  199. if (mq->pages_used) {
  200. uint32_t dst_page = mq->pages_used - 1;
  201. uint32_t dst_offset = mq->page_bytes[dst_page];
  202. if (dst_offset + page_bytes[0] < uint32_t(PAGE_SIZE_BYTES)) {
  203. memcpy(mq->pages[dst_page]->data + dst_offset, pages[0]->data, page_bytes[0]);
  204. mq->page_bytes[dst_page] += page_bytes[0];
  205. src_page++;
  206. }
  207. }
  208. }
  209. // Any other possibly existing source page needs to be added.
  210. if (mq->pages_used + (pages_used - src_page) > mq->max_pages) {
  211. ERR_PRINT("Failed appending thread queue. Message queue out of memory. " + mq->error_text);
  212. mq->statistics();
  213. mq->mutex.unlock();
  214. return ERR_OUT_OF_MEMORY;
  215. }
  216. for (; src_page < pages_used; src_page++) {
  217. mq->_add_page();
  218. memcpy(mq->pages[mq->pages_used - 1]->data, pages[src_page]->data, page_bytes[src_page]);
  219. mq->page_bytes[mq->pages_used - 1] = page_bytes[src_page];
  220. }
  221. mq->mutex.unlock();
  222. page_bytes[0] = 0;
  223. pages_used = 1;
  224. return OK;
  225. }
  226. Error CallQueue::flush() {
  227. // Thread overrides are not meant to be flushed, but appended to the main one.
  228. if (unlikely(this == MessageQueue::thread_singleton)) {
  229. return _transfer_messages_to_main_queue();
  230. }
  231. LOCK_MUTEX;
  232. if (pages.size() == 0) {
  233. // Never allocated
  234. UNLOCK_MUTEX;
  235. return OK; // Do nothing.
  236. }
  237. if (flushing) {
  238. UNLOCK_MUTEX;
  239. return ERR_BUSY;
  240. }
  241. flushing = true;
  242. uint32_t i = 0;
  243. uint32_t offset = 0;
  244. while (i < pages_used && offset < page_bytes[i]) {
  245. Page *page = pages[i];
  246. //lock on each iteration, so a call can re-add itself to the message queue
  247. Message *message = (Message *)&page->data[offset];
  248. uint32_t advance = sizeof(Message);
  249. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  250. advance += sizeof(Variant) * message->args;
  251. }
  252. //pre-advance so this function is reentrant
  253. offset += advance;
  254. Object *target = message->callable.get_object();
  255. UNLOCK_MUTEX;
  256. #ifdef DEBUG_ENABLED
  257. if (!message->callable.is_valid()) {
  258. // The editor would cause many of these.
  259. if (!Engine::get_singleton()->is_editor_hint()) {
  260. ERR_PRINT("Trying to execute a deferred call/notification/set on a previously freed instance. Consider using queue_free() instead of free().");
  261. }
  262. } else
  263. #endif
  264. {
  265. switch (message->type & FLAG_MASK) {
  266. case TYPE_CALL: {
  267. if (target || (message->type & FLAG_NULL_IS_OK)) {
  268. Variant *args = (Variant *)(message + 1);
  269. _call_function(message->callable, args, message->args, message->type & FLAG_SHOW_ERROR);
  270. }
  271. } break;
  272. case TYPE_NOTIFICATION: {
  273. if (target) {
  274. target->notification(message->notification);
  275. }
  276. } break;
  277. case TYPE_SET: {
  278. if (target) {
  279. Variant *arg = (Variant *)(message + 1);
  280. target->set(message->callable.get_method(), *arg);
  281. }
  282. } break;
  283. }
  284. }
  285. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  286. Variant *args = (Variant *)(message + 1);
  287. for (int k = 0; k < message->args; k++) {
  288. args[k].~Variant();
  289. }
  290. }
  291. message->~Message();
  292. LOCK_MUTEX;
  293. if (offset == page_bytes[i]) {
  294. i++;
  295. offset = 0;
  296. }
  297. }
  298. page_bytes[0] = 0;
  299. pages_used = 1;
  300. flushing = false;
  301. UNLOCK_MUTEX;
  302. return OK;
  303. }
  304. void CallQueue::clear() {
  305. LOCK_MUTEX;
  306. if (pages.size() == 0) {
  307. UNLOCK_MUTEX;
  308. return; // Nothing to clear.
  309. }
  310. for (uint32_t i = 0; i < pages_used; i++) {
  311. uint32_t offset = 0;
  312. while (offset < page_bytes[i]) {
  313. Page *page = pages[i];
  314. //lock on each iteration, so a call can re-add itself to the message queue
  315. Message *message = (Message *)&page->data[offset];
  316. uint32_t advance = sizeof(Message);
  317. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  318. advance += sizeof(Variant) * message->args;
  319. }
  320. offset += advance;
  321. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  322. Variant *args = (Variant *)(message + 1);
  323. for (int k = 0; k < message->args; k++) {
  324. args[k].~Variant();
  325. }
  326. }
  327. message->~Message();
  328. }
  329. }
  330. pages_used = 1;
  331. page_bytes[0] = 0;
  332. UNLOCK_MUTEX;
  333. }
  334. void CallQueue::statistics() {
  335. LOCK_MUTEX;
  336. HashMap<StringName, int> set_count;
  337. HashMap<int, int> notify_count;
  338. HashMap<Callable, int> call_count;
  339. int null_count = 0;
  340. for (uint32_t i = 0; i < pages_used; i++) {
  341. uint32_t offset = 0;
  342. while (offset < page_bytes[i]) {
  343. Page *page = pages[i];
  344. //lock on each iteration, so a call can re-add itself to the message queue
  345. Message *message = (Message *)&page->data[offset];
  346. uint32_t advance = sizeof(Message);
  347. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  348. advance += sizeof(Variant) * message->args;
  349. }
  350. Object *target = message->callable.get_object();
  351. bool null_target = true;
  352. switch (message->type & FLAG_MASK) {
  353. case TYPE_CALL: {
  354. if (target || (message->type & FLAG_NULL_IS_OK)) {
  355. if (!call_count.has(message->callable)) {
  356. call_count[message->callable] = 0;
  357. }
  358. call_count[message->callable]++;
  359. null_target = false;
  360. }
  361. } break;
  362. case TYPE_NOTIFICATION: {
  363. if (target) {
  364. if (!notify_count.has(message->notification)) {
  365. notify_count[message->notification] = 0;
  366. }
  367. notify_count[message->notification]++;
  368. null_target = false;
  369. }
  370. } break;
  371. case TYPE_SET: {
  372. if (target) {
  373. StringName t = message->callable.get_method();
  374. if (!set_count.has(t)) {
  375. set_count[t] = 0;
  376. }
  377. set_count[t]++;
  378. null_target = false;
  379. }
  380. } break;
  381. }
  382. if (null_target) {
  383. //object was deleted
  384. print_line("Object was deleted while awaiting a callback");
  385. null_count++;
  386. }
  387. offset += advance;
  388. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  389. Variant *args = (Variant *)(message + 1);
  390. for (int k = 0; k < message->args; k++) {
  391. args[k].~Variant();
  392. }
  393. }
  394. message->~Message();
  395. }
  396. }
  397. print_line("TOTAL PAGES: " + itos(pages_used) + " (" + itos(pages_used * PAGE_SIZE_BYTES) + " bytes).");
  398. print_line("NULL count: " + itos(null_count));
  399. for (const KeyValue<StringName, int> &E : set_count) {
  400. print_line("SET " + E.key + ": " + itos(E.value));
  401. }
  402. for (const KeyValue<Callable, int> &E : call_count) {
  403. print_line("CALL " + E.key + ": " + itos(E.value));
  404. }
  405. for (const KeyValue<int, int> &E : notify_count) {
  406. print_line("NOTIFY " + itos(E.key) + ": " + itos(E.value));
  407. }
  408. UNLOCK_MUTEX;
  409. }
  410. bool CallQueue::is_flushing() const {
  411. return flushing;
  412. }
  413. bool CallQueue::has_messages() const {
  414. if (pages_used == 0) {
  415. return false;
  416. }
  417. if (pages_used == 1 && page_bytes[0] == 0) {
  418. return false;
  419. }
  420. return true;
  421. }
  422. int CallQueue::get_max_buffer_usage() const {
  423. return pages.size() * PAGE_SIZE_BYTES;
  424. }
  425. CallQueue::CallQueue(Allocator *p_custom_allocator, uint32_t p_max_pages, const String &p_error_text) {
  426. if (p_custom_allocator) {
  427. allocator = p_custom_allocator;
  428. allocator_is_custom = true;
  429. } else {
  430. allocator = memnew(Allocator(16)); // 16 elements per allocator page, 64kb per allocator page. Anything small will do, though.
  431. allocator_is_custom = false;
  432. }
  433. max_pages = p_max_pages;
  434. error_text = p_error_text;
  435. }
  436. CallQueue::~CallQueue() {
  437. clear();
  438. // Let go of pages.
  439. for (uint32_t i = 0; i < pages.size(); i++) {
  440. allocator->free(pages[i]);
  441. }
  442. if (!allocator_is_custom) {
  443. memdelete(allocator);
  444. }
  445. // This is done here to avoid a circular dependency between the sanity checks and the thread singleton pointer.
  446. if (this == MessageQueue::thread_singleton) {
  447. MessageQueue::thread_singleton = nullptr;
  448. }
  449. }
  450. //////////////////////
  451. CallQueue *MessageQueue::main_singleton = nullptr;
  452. thread_local CallQueue *MessageQueue::thread_singleton = nullptr;
  453. void MessageQueue::set_thread_singleton_override(CallQueue *p_thread_singleton) {
  454. DEV_ASSERT(p_thread_singleton); // To unset the thread singleton, don't call this with nullptr, but just memfree() it.
  455. #ifdef DEV_ENABLED
  456. if (thread_singleton) {
  457. thread_singleton->is_current_thread_override = false;
  458. }
  459. #endif
  460. thread_singleton = p_thread_singleton;
  461. #ifdef DEV_ENABLED
  462. if (thread_singleton) {
  463. thread_singleton->is_current_thread_override = true;
  464. }
  465. #endif
  466. }
  467. MessageQueue::MessageQueue() :
  468. CallQueue(nullptr,
  469. 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,
  470. "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.") {
  471. ERR_FAIL_COND_MSG(main_singleton != nullptr, "A MessageQueue singleton already exists.");
  472. main_singleton = this;
  473. }
  474. MessageQueue::~MessageQueue() {
  475. main_singleton = nullptr;
  476. }