message_queue.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. void CallQueue::_add_page() {
  36. if (pages_used == page_messages.size()) {
  37. pages.push_back(allocator->alloc());
  38. page_messages.push_back(0);
  39. }
  40. page_messages[pages_used] = 0;
  41. pages_used++;
  42. page_offset = 0;
  43. }
  44. Error CallQueue::push_callp(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  45. return push_callablep(Callable(p_id, p_method), p_args, p_argcount, p_show_error);
  46. }
  47. Error CallQueue::push_callp(Object *p_object, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  48. return push_callp(p_object->get_instance_id(), p_method, p_args, p_argcount, p_show_error);
  49. }
  50. Error CallQueue::push_notification(Object *p_object, int p_notification) {
  51. return push_notification(p_object->get_instance_id(), p_notification);
  52. }
  53. Error CallQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
  54. return push_set(p_object->get_instance_id(), p_prop, p_value);
  55. }
  56. Error CallQueue::push_callablep(const Callable &p_callable, const Variant **p_args, int p_argcount, bool p_show_error) {
  57. mutex.lock();
  58. uint32_t room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
  59. 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.");
  60. _ensure_first_page();
  61. if ((page_offset + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  62. if (room_needed > uint32_t(PAGE_SIZE_BYTES) || pages_used == max_pages) {
  63. ERR_PRINT("Failed method: " + p_callable + ". Message queue out of memory. " + error_text);
  64. statistics();
  65. mutex.unlock();
  66. return ERR_OUT_OF_MEMORY;
  67. }
  68. _add_page();
  69. }
  70. Page *page = pages[pages_used - 1];
  71. uint8_t *buffer_end = &page->data[page_offset];
  72. Message *msg = memnew_placement(buffer_end, Message);
  73. msg->args = p_argcount;
  74. msg->callable = p_callable;
  75. msg->type = TYPE_CALL;
  76. if (p_show_error) {
  77. msg->type |= FLAG_SHOW_ERROR;
  78. }
  79. buffer_end += sizeof(Message);
  80. for (int i = 0; i < p_argcount; i++) {
  81. Variant *v = memnew_placement(buffer_end, Variant);
  82. buffer_end += sizeof(Variant);
  83. *v = *p_args[i];
  84. }
  85. page_messages[pages_used - 1]++;
  86. page_offset += room_needed;
  87. mutex.unlock();
  88. return OK;
  89. }
  90. Error CallQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
  91. mutex.lock();
  92. uint32_t room_needed = sizeof(Message) + sizeof(Variant);
  93. _ensure_first_page();
  94. if ((page_offset + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  95. if (pages_used == max_pages) {
  96. String type;
  97. if (ObjectDB::get_instance(p_id)) {
  98. type = ObjectDB::get_instance(p_id)->get_class();
  99. }
  100. ERR_PRINT("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id) + ". Message queue out of memory. " + error_text);
  101. statistics();
  102. mutex.unlock();
  103. return ERR_OUT_OF_MEMORY;
  104. }
  105. _add_page();
  106. }
  107. Page *page = pages[pages_used - 1];
  108. uint8_t *buffer_end = &page->data[page_offset];
  109. Message *msg = memnew_placement(buffer_end, Message);
  110. msg->args = 1;
  111. msg->callable = Callable(p_id, p_prop);
  112. msg->type = TYPE_SET;
  113. buffer_end += sizeof(Message);
  114. Variant *v = memnew_placement(buffer_end, Variant);
  115. *v = p_value;
  116. page_messages[pages_used - 1]++;
  117. page_offset += room_needed;
  118. mutex.unlock();
  119. return OK;
  120. }
  121. Error CallQueue::push_notification(ObjectID p_id, int p_notification) {
  122. ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
  123. mutex.lock();
  124. uint32_t room_needed = sizeof(Message);
  125. _ensure_first_page();
  126. if ((page_offset + room_needed) > uint32_t(PAGE_SIZE_BYTES)) {
  127. if (pages_used == max_pages) {
  128. ERR_PRINT("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id) + ". Message queue out of memory. " + error_text);
  129. statistics();
  130. mutex.unlock();
  131. return ERR_OUT_OF_MEMORY;
  132. }
  133. _add_page();
  134. }
  135. Page *page = pages[pages_used - 1];
  136. uint8_t *buffer_end = &page->data[page_offset];
  137. Message *msg = memnew_placement(buffer_end, Message);
  138. msg->type = TYPE_NOTIFICATION;
  139. msg->callable = Callable(p_id, CoreStringNames::get_singleton()->notification); //name is meaningless but callable needs it
  140. //msg->target;
  141. msg->notification = p_notification;
  142. page_messages[pages_used - 1]++;
  143. page_offset += room_needed;
  144. mutex.unlock();
  145. return OK;
  146. }
  147. void CallQueue::_call_function(const Callable &p_callable, const Variant *p_args, int p_argcount, bool p_show_error) {
  148. const Variant **argptrs = nullptr;
  149. if (p_argcount) {
  150. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
  151. for (int i = 0; i < p_argcount; i++) {
  152. argptrs[i] = &p_args[i];
  153. }
  154. }
  155. Callable::CallError ce;
  156. Variant ret;
  157. p_callable.callp(argptrs, p_argcount, ret, ce);
  158. if (p_show_error && ce.error != Callable::CallError::CALL_OK) {
  159. ERR_PRINT("Error calling deferred method: " + Variant::get_callable_error_text(p_callable, argptrs, p_argcount, ce) + ".");
  160. }
  161. }
  162. Error CallQueue::flush() {
  163. mutex.lock();
  164. if (pages.size() == 0) {
  165. // Never allocated
  166. mutex.unlock();
  167. return OK; // Do nothing.
  168. }
  169. if (flushing) {
  170. mutex.unlock();
  171. return ERR_BUSY;
  172. }
  173. flushing = true;
  174. uint32_t i = 0;
  175. uint32_t j = 0;
  176. uint32_t offset = 0;
  177. while (i < pages_used && j < page_messages[i]) {
  178. Page *page = pages[i];
  179. //lock on each iteration, so a call can re-add itself to the message queue
  180. Message *message = (Message *)&page->data[offset];
  181. uint32_t advance = sizeof(Message);
  182. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  183. advance += sizeof(Variant) * message->args;
  184. }
  185. //pre-advance so this function is reentrant
  186. offset += advance;
  187. Object *target = message->callable.get_object();
  188. mutex.unlock();
  189. if (target != nullptr) {
  190. switch (message->type & FLAG_MASK) {
  191. case TYPE_CALL: {
  192. Variant *args = (Variant *)(message + 1);
  193. // messages don't expect a return value
  194. _call_function(message->callable, args, message->args, message->type & FLAG_SHOW_ERROR);
  195. } break;
  196. case TYPE_NOTIFICATION: {
  197. // messages don't expect a return value
  198. target->notification(message->notification);
  199. } break;
  200. case TYPE_SET: {
  201. Variant *arg = (Variant *)(message + 1);
  202. // messages don't expect a return value
  203. target->set(message->callable.get_method(), *arg);
  204. } break;
  205. }
  206. }
  207. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  208. Variant *args = (Variant *)(message + 1);
  209. for (int k = 0; k < message->args; k++) {
  210. args[k].~Variant();
  211. }
  212. }
  213. message->~Message();
  214. mutex.lock();
  215. j++;
  216. if (j == page_messages[i]) {
  217. j = 0;
  218. i++;
  219. offset = 0;
  220. }
  221. }
  222. page_messages[0] = 0;
  223. page_offset = 0;
  224. pages_used = 1;
  225. flushing = false;
  226. mutex.unlock();
  227. return OK;
  228. }
  229. void CallQueue::clear() {
  230. mutex.lock();
  231. if (pages.size() == 0) {
  232. mutex.unlock();
  233. return; // Nothing to clear.
  234. }
  235. for (uint32_t i = 0; i < pages_used; i++) {
  236. uint32_t offset = 0;
  237. for (uint32_t j = 0; j < page_messages[i]; j++) {
  238. Page *page = pages[i];
  239. //lock on each iteration, so a call can re-add itself to the message queue
  240. Message *message = (Message *)&page->data[offset];
  241. uint32_t advance = sizeof(Message);
  242. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  243. advance += sizeof(Variant) * message->args;
  244. }
  245. //pre-advance so this function is reentrant
  246. offset += advance;
  247. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  248. Variant *args = (Variant *)(message + 1);
  249. for (int k = 0; k < message->args; k++) {
  250. args[k].~Variant();
  251. }
  252. }
  253. message->~Message();
  254. }
  255. }
  256. pages_used = 1;
  257. page_offset = 0;
  258. page_messages[0] = 0;
  259. mutex.unlock();
  260. }
  261. void CallQueue::statistics() {
  262. mutex.lock();
  263. HashMap<StringName, int> set_count;
  264. HashMap<int, int> notify_count;
  265. HashMap<Callable, int> call_count;
  266. int null_count = 0;
  267. for (uint32_t i = 0; i < pages_used; i++) {
  268. uint32_t offset = 0;
  269. for (uint32_t j = 0; j < page_messages[i]; j++) {
  270. Page *page = pages[i];
  271. //lock on each iteration, so a call can re-add itself to the message queue
  272. Message *message = (Message *)&page->data[offset];
  273. uint32_t advance = sizeof(Message);
  274. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  275. advance += sizeof(Variant) * message->args;
  276. }
  277. Object *target = message->callable.get_object();
  278. if (target != nullptr) {
  279. switch (message->type & FLAG_MASK) {
  280. case TYPE_CALL: {
  281. if (!call_count.has(message->callable)) {
  282. call_count[message->callable] = 0;
  283. }
  284. call_count[message->callable]++;
  285. } break;
  286. case TYPE_NOTIFICATION: {
  287. if (!notify_count.has(message->notification)) {
  288. notify_count[message->notification] = 0;
  289. }
  290. notify_count[message->notification]++;
  291. } break;
  292. case TYPE_SET: {
  293. StringName t = message->callable.get_method();
  294. if (!set_count.has(t)) {
  295. set_count[t] = 0;
  296. }
  297. set_count[t]++;
  298. } break;
  299. }
  300. } else {
  301. //object was deleted
  302. print_line("Object was deleted while awaiting a callback");
  303. null_count++;
  304. }
  305. //pre-advance so this function is reentrant
  306. offset += advance;
  307. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  308. Variant *args = (Variant *)(message + 1);
  309. for (int k = 0; k < message->args; k++) {
  310. args[k].~Variant();
  311. }
  312. }
  313. message->~Message();
  314. }
  315. }
  316. print_line("TOTAL PAGES: " + itos(pages_used) + " (" + itos(pages_used * PAGE_SIZE_BYTES) + " bytes).");
  317. print_line("NULL count: " + itos(null_count));
  318. for (const KeyValue<StringName, int> &E : set_count) {
  319. print_line("SET " + E.key + ": " + itos(E.value));
  320. }
  321. for (const KeyValue<Callable, int> &E : call_count) {
  322. print_line("CALL " + E.key + ": " + itos(E.value));
  323. }
  324. for (const KeyValue<int, int> &E : notify_count) {
  325. print_line("NOTIFY " + itos(E.key) + ": " + itos(E.value));
  326. }
  327. mutex.unlock();
  328. }
  329. bool CallQueue::is_flushing() const {
  330. return flushing;
  331. }
  332. int CallQueue::get_max_buffer_usage() const {
  333. return pages.size() * PAGE_SIZE_BYTES;
  334. }
  335. CallQueue::CallQueue(Allocator *p_custom_allocator, uint32_t p_max_pages, const String &p_error_text) {
  336. if (p_custom_allocator) {
  337. allocator = p_custom_allocator;
  338. allocator_is_custom = true;
  339. } else {
  340. allocator = memnew(Allocator(16)); // 16 elements per allocator page, 64kb per allocator page. Anything small will do, though.
  341. allocator_is_custom = false;
  342. }
  343. max_pages = p_max_pages;
  344. error_text = p_error_text;
  345. }
  346. CallQueue::~CallQueue() {
  347. clear();
  348. // Let go of pages.
  349. for (uint32_t i = 0; i < pages.size(); i++) {
  350. allocator->free(pages[i]);
  351. }
  352. if (!allocator_is_custom) {
  353. memdelete(allocator);
  354. }
  355. }
  356. //////////////////////
  357. MessageQueue *MessageQueue::singleton = nullptr;
  358. MessageQueue::MessageQueue() :
  359. CallQueue(nullptr,
  360. 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,
  361. "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.") {
  362. ERR_FAIL_COND_MSG(singleton != nullptr, "A MessageQueue singleton already exists.");
  363. singleton = this;
  364. }
  365. MessageQueue::~MessageQueue() {
  366. singleton = nullptr;
  367. }