message_queue.cpp 16 KB

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