message_queue.cpp 17 KB

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