csharp_script.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926
  1. /**************************************************************************/
  2. /* csharp_script.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 "csharp_script.h"
  31. #include "godotsharp_dirs.h"
  32. #include "managed_callable.h"
  33. #include "mono_gd/gd_mono_cache.h"
  34. #include "signal_awaiter_utils.h"
  35. #include "utils/macros.h"
  36. #include "utils/naming_utils.h"
  37. #include "utils/path_utils.h"
  38. #include "utils/string_utils.h"
  39. #ifdef DEBUG_METHODS_ENABLED
  40. #include "class_db_api_json.h"
  41. #endif
  42. #ifdef TOOLS_ENABLED
  43. #include "editor/editor_internal_calls.h"
  44. #include "editor/script_templates/templates.gen.h"
  45. #endif
  46. #include "core/config/project_settings.h"
  47. #include "core/debugger/engine_debugger.h"
  48. #include "core/debugger/script_debugger.h"
  49. #include "core/io/file_access.h"
  50. #include "core/os/mutex.h"
  51. #include "core/os/os.h"
  52. #include "core/os/thread.h"
  53. #include "servers/text_server.h"
  54. #ifdef TOOLS_ENABLED
  55. #include "core/os/keyboard.h"
  56. #include "editor/editor_file_system.h"
  57. #include "editor/editor_node.h"
  58. #include "editor/editor_settings.h"
  59. #include "editor/inspector_dock.h"
  60. #include "editor/node_dock.h"
  61. #endif
  62. #include <stdint.h>
  63. // Types that will be skipped over (in favor of their base types) when setting up instance bindings.
  64. // This must be a superset of `ignored_types` in bindings_generator.cpp.
  65. const Vector<String> ignored_types = {};
  66. #ifdef TOOLS_ENABLED
  67. static bool _create_project_solution_if_needed() {
  68. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
  69. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolutionIfNeeded");
  70. }
  71. #endif
  72. CSharpLanguage *CSharpLanguage::singleton = nullptr;
  73. GDExtensionInstanceBindingCallbacks CSharpLanguage::_instance_binding_callbacks = {
  74. &_instance_binding_create_callback,
  75. &_instance_binding_free_callback,
  76. &_instance_binding_reference_callback
  77. };
  78. String CSharpLanguage::get_name() const {
  79. return "C#";
  80. }
  81. String CSharpLanguage::get_type() const {
  82. return "CSharpScript";
  83. }
  84. String CSharpLanguage::get_extension() const {
  85. return "cs";
  86. }
  87. void CSharpLanguage::init() {
  88. #ifdef TOOLS_ENABLED
  89. if (OS::get_singleton()->get_cmdline_args().find("--generate-mono-glue")) {
  90. print_verbose(".NET: Skipping runtime initialization because glue generation is enabled.");
  91. return;
  92. }
  93. #endif
  94. #ifdef DEBUG_METHODS_ENABLED
  95. if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
  96. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  97. #ifdef TOOLS_ENABLED
  98. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  99. #endif
  100. }
  101. #endif
  102. GLOBAL_DEF("dotnet/project/assembly_name", "");
  103. #ifdef TOOLS_ENABLED
  104. GLOBAL_DEF("dotnet/project/solution_directory", "");
  105. GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
  106. #endif
  107. #ifdef TOOLS_ENABLED
  108. EditorNode::add_init_callback(&_editor_init_callback);
  109. #endif
  110. gdmono = memnew(GDMono);
  111. // Initialize only if the project uses C#.
  112. if (gdmono->should_initialize()) {
  113. gdmono->initialize();
  114. }
  115. }
  116. void CSharpLanguage::finish() {
  117. finalize();
  118. }
  119. void CSharpLanguage::finalize() {
  120. if (finalized) {
  121. return;
  122. }
  123. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  124. GDMonoCache::managed_callbacks.DisposablesTracker_OnGodotShuttingDown();
  125. }
  126. finalizing = true;
  127. // Make sure all script binding gchandles are released before finalizing GDMono.
  128. for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  129. CSharpScriptBinding &script_binding = E.value;
  130. if (!script_binding.gchandle.is_released()) {
  131. script_binding.gchandle.release();
  132. script_binding.inited = false;
  133. }
  134. // Make sure we clear all the instance binding callbacks so they don't get called
  135. // after finalizing the C# language.
  136. script_binding.owner->free_instance_binding(this);
  137. }
  138. if (gdmono) {
  139. memdelete(gdmono);
  140. gdmono = nullptr;
  141. }
  142. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  143. script_bindings.clear();
  144. #ifdef DEBUG_ENABLED
  145. for (const KeyValue<ObjectID, int> &E : unsafe_object_references) {
  146. const ObjectID &id = E.key;
  147. Object *obj = ObjectDB::get_instance(id);
  148. if (obj) {
  149. ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
  150. } else {
  151. ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
  152. }
  153. }
  154. #endif
  155. memdelete(managed_callable_middleman);
  156. finalizing = false;
  157. finalized = true;
  158. }
  159. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  160. static const char *_reserved_words[] = {
  161. // Reserved keywords
  162. "abstract",
  163. "as",
  164. "base",
  165. "bool",
  166. "break",
  167. "byte",
  168. "case",
  169. "catch",
  170. "char",
  171. "checked",
  172. "class",
  173. "const",
  174. "continue",
  175. "decimal",
  176. "default",
  177. "delegate",
  178. "do",
  179. "double",
  180. "else",
  181. "enum",
  182. "event",
  183. "explicit",
  184. "extern",
  185. "false",
  186. "finally",
  187. "fixed",
  188. "float",
  189. "for",
  190. "foreach",
  191. "goto",
  192. "if",
  193. "implicit",
  194. "in",
  195. "int",
  196. "interface",
  197. "internal",
  198. "is",
  199. "lock",
  200. "long",
  201. "namespace",
  202. "new",
  203. "null",
  204. "object",
  205. "operator",
  206. "out",
  207. "override",
  208. "params",
  209. "private",
  210. "protected",
  211. "public",
  212. "readonly",
  213. "ref",
  214. "return",
  215. "sbyte",
  216. "sealed",
  217. "short",
  218. "sizeof",
  219. "stackalloc",
  220. "static",
  221. "string",
  222. "struct",
  223. "switch",
  224. "this",
  225. "throw",
  226. "true",
  227. "try",
  228. "typeof",
  229. "uint",
  230. "ulong",
  231. "unchecked",
  232. "unsafe",
  233. "ushort",
  234. "using",
  235. "virtual",
  236. "void",
  237. "volatile",
  238. "while",
  239. // Contextual keywords. Not reserved words, but I guess we should include
  240. // them because this seems to be used only for syntax highlighting.
  241. "add",
  242. "alias",
  243. "ascending",
  244. "async",
  245. "await",
  246. "by",
  247. "descending",
  248. "dynamic",
  249. "equals",
  250. "from",
  251. "get",
  252. "global",
  253. "group",
  254. "into",
  255. "join",
  256. "let",
  257. "nameof",
  258. "on",
  259. "orderby",
  260. "partial",
  261. "remove",
  262. "select",
  263. "set",
  264. "value",
  265. "var",
  266. "when",
  267. "where",
  268. "yield",
  269. nullptr
  270. };
  271. const char **w = _reserved_words;
  272. while (*w) {
  273. p_words->push_back(*w);
  274. w++;
  275. }
  276. }
  277. bool CSharpLanguage::is_control_flow_keyword(const String &p_keyword) const {
  278. return p_keyword == "break" ||
  279. p_keyword == "case" ||
  280. p_keyword == "catch" ||
  281. p_keyword == "continue" ||
  282. p_keyword == "default" ||
  283. p_keyword == "do" ||
  284. p_keyword == "else" ||
  285. p_keyword == "finally" ||
  286. p_keyword == "for" ||
  287. p_keyword == "foreach" ||
  288. p_keyword == "goto" ||
  289. p_keyword == "if" ||
  290. p_keyword == "return" ||
  291. p_keyword == "switch" ||
  292. p_keyword == "throw" ||
  293. p_keyword == "try" ||
  294. p_keyword == "while";
  295. }
  296. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  297. p_delimiters->push_back("//"); // single-line comment
  298. p_delimiters->push_back("/* */"); // delimited comment
  299. }
  300. void CSharpLanguage::get_doc_comment_delimiters(List<String> *p_delimiters) const {
  301. p_delimiters->push_back("///"); // single-line doc comment
  302. p_delimiters->push_back("/** */"); // delimited doc comment
  303. }
  304. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  305. p_delimiters->push_back("' '"); // character literal
  306. p_delimiters->push_back("\" \""); // regular string literal
  307. p_delimiters->push_back("@\" \""); // verbatim string literal
  308. // Generic string highlighting suffices as a workaround for now.
  309. }
  310. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  311. String base_class = pascal_to_pascal_case(p_base_class_name);
  312. if (p_class_name == base_class) {
  313. base_class = "Godot." + base_class;
  314. }
  315. return base_class;
  316. }
  317. bool CSharpLanguage::is_using_templates() {
  318. return true;
  319. }
  320. Ref<Script> CSharpLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
  321. Ref<CSharpScript> scr;
  322. scr.instantiate();
  323. String class_name_no_spaces = p_class_name.replace(" ", "_");
  324. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  325. String processed_template = p_template;
  326. processed_template = processed_template.replace("_BINDINGS_NAMESPACE_", BINDINGS_NAMESPACE)
  327. .replace("_BASE_", base_class_name)
  328. .replace("_CLASS_", class_name_no_spaces)
  329. .replace("_TS_", _get_indentation());
  330. scr->set_source_code(processed_template);
  331. return scr;
  332. }
  333. Vector<ScriptLanguage::ScriptTemplate> CSharpLanguage::get_built_in_templates(const StringName &p_object) {
  334. Vector<ScriptLanguage::ScriptTemplate> templates;
  335. #ifdef TOOLS_ENABLED
  336. for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
  337. if (TEMPLATES[i].inherit == p_object) {
  338. templates.append(TEMPLATES[i]);
  339. }
  340. }
  341. #endif
  342. return templates;
  343. }
  344. String CSharpLanguage::validate_path(const String &p_path) const {
  345. String class_name = p_path.get_file().get_basename();
  346. List<String> keywords;
  347. get_reserved_words(&keywords);
  348. if (keywords.find(class_name)) {
  349. return RTR("Class name can't be a reserved keyword");
  350. }
  351. if (!TS->is_valid_identifier(class_name)) {
  352. return RTR("Class name must be a valid identifier");
  353. }
  354. return "";
  355. }
  356. Script *CSharpLanguage::create_script() const {
  357. return memnew(CSharpScript);
  358. }
  359. bool CSharpLanguage::supports_builtin_mode() const {
  360. return false;
  361. }
  362. ScriptLanguage::ScriptNameCasing CSharpLanguage::preferred_file_name_casing() const {
  363. return SCRIPT_NAME_CASING_PASCAL_CASE;
  364. }
  365. #ifdef TOOLS_ENABLED
  366. String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
  367. // The make_function() API does not work for C# scripts.
  368. // It will always append the generated function at the very end of the script. In C#, it will break compilation by
  369. // appending code after the final closing bracket (either the class' or the namespace's).
  370. // To prevent issues, we have can_make_function() returning false, and make_function() is never implemented.
  371. return String();
  372. }
  373. #else
  374. String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
  375. return String();
  376. }
  377. #endif
  378. String CSharpLanguage::_get_indentation() const {
  379. #ifdef TOOLS_ENABLED
  380. if (Engine::get_singleton()->is_editor_hint()) {
  381. bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
  382. if (use_space_indentation) {
  383. int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
  384. return String(" ").repeat(indent_size);
  385. }
  386. }
  387. #endif
  388. return "\t";
  389. }
  390. bool CSharpLanguage::handles_global_class_type(const String &p_type) const {
  391. return p_type == get_type();
  392. }
  393. String CSharpLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
  394. String class_name;
  395. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetGlobalClassName(&p_path, r_base_type, r_icon_path, &class_name);
  396. return class_name;
  397. }
  398. String CSharpLanguage::debug_get_error() const {
  399. return _debug_error;
  400. }
  401. int CSharpLanguage::debug_get_stack_level_count() const {
  402. if (_debug_parse_err_line >= 0) {
  403. return 1;
  404. }
  405. // TODO: StackTrace
  406. return 1;
  407. }
  408. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  409. if (_debug_parse_err_line >= 0) {
  410. return _debug_parse_err_line;
  411. }
  412. // TODO: StackTrace
  413. return 1;
  414. }
  415. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  416. if (_debug_parse_err_line >= 0) {
  417. return String();
  418. }
  419. // TODO: StackTrace
  420. return String();
  421. }
  422. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  423. if (_debug_parse_err_line >= 0) {
  424. return _debug_parse_err_file;
  425. }
  426. // TODO: StackTrace
  427. return String();
  428. }
  429. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  430. #ifdef DEBUG_ENABLED
  431. // Printing an error here will result in endless recursion, so we must be careful
  432. static thread_local bool _recursion_flag_ = false;
  433. if (_recursion_flag_) {
  434. return Vector<StackInfo>();
  435. }
  436. _recursion_flag_ = true;
  437. SCOPE_EXIT {
  438. _recursion_flag_ = false; // clang-format off
  439. }; // clang-format on
  440. if (!gdmono || !gdmono->is_runtime_initialized()) {
  441. return Vector<StackInfo>();
  442. }
  443. Vector<StackInfo> si;
  444. if (GDMonoCache::godot_api_cache_updated) {
  445. GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
  446. }
  447. return si;
  448. #else
  449. return Vector<StackInfo>();
  450. #endif
  451. }
  452. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  453. #ifdef DEBUG_ENABLED
  454. MutexLock lock(unsafe_object_references_lock);
  455. ObjectID id = p_obj->get_instance_id();
  456. unsafe_object_references[id]++;
  457. #endif
  458. }
  459. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  460. #ifdef DEBUG_ENABLED
  461. MutexLock lock(unsafe_object_references_lock);
  462. ObjectID id = p_obj->get_instance_id();
  463. HashMap<ObjectID, int>::Iterator elem = unsafe_object_references.find(id);
  464. ERR_FAIL_NULL(elem);
  465. if (--elem->value == 0) {
  466. unsafe_object_references.remove(elem);
  467. }
  468. #endif
  469. }
  470. void CSharpLanguage::frame() {
  471. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  472. GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
  473. }
  474. }
  475. struct CSharpScriptDepSort {
  476. // Must support sorting so inheritance works properly (parent must be reloaded first)
  477. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  478. if (A == B) {
  479. // Shouldn't happen but just in case...
  480. return false;
  481. }
  482. const Script *I = B->get_base_script().ptr();
  483. while (I) {
  484. if (I == A.ptr()) {
  485. // A is a base of B
  486. return true;
  487. }
  488. I = I->get_base_script().ptr();
  489. }
  490. // A isn't a base of B
  491. return false;
  492. }
  493. };
  494. void CSharpLanguage::reload_all_scripts() {
  495. #ifdef GD_MONO_HOT_RELOAD
  496. if (is_assembly_reloading_needed()) {
  497. reload_assemblies(false);
  498. }
  499. #endif
  500. }
  501. void CSharpLanguage::reload_scripts(const Array &p_scripts, bool p_soft_reload) {
  502. #ifdef GD_MONO_HOT_RELOAD
  503. if (is_assembly_reloading_needed()) {
  504. reload_assemblies(p_soft_reload);
  505. }
  506. #endif
  507. }
  508. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  509. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  510. #ifdef TOOLS_ENABLED
  511. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  512. #endif
  513. #ifdef GD_MONO_HOT_RELOAD
  514. if (is_assembly_reloading_needed()) {
  515. reload_assemblies(p_soft_reload);
  516. }
  517. #endif
  518. }
  519. #ifdef GD_MONO_HOT_RELOAD
  520. bool CSharpLanguage::is_assembly_reloading_needed() {
  521. ERR_FAIL_NULL_V(gdmono, false);
  522. if (!gdmono->is_runtime_initialized()) {
  523. return false;
  524. }
  525. String assembly_path = gdmono->get_project_assembly_path();
  526. if (!assembly_path.is_empty()) {
  527. if (!FileAccess::exists(assembly_path)) {
  528. return false; // No assembly to load
  529. }
  530. if (FileAccess::get_modified_time(assembly_path) <= gdmono->get_project_assembly_modified_time()) {
  531. return false; // Already up to date
  532. }
  533. } else {
  534. String assembly_name = path::get_csharp_project_name();
  535. assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
  536. .path_join(assembly_name + ".dll");
  537. assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
  538. if (!FileAccess::exists(assembly_path)) {
  539. return false; // No assembly to load
  540. }
  541. }
  542. return true;
  543. }
  544. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  545. ERR_FAIL_NULL(gdmono);
  546. if (!gdmono->is_runtime_initialized()) {
  547. return;
  548. }
  549. if (!Engine::get_singleton()->is_editor_hint()) {
  550. // We disable collectible assemblies in the game player, because the limitations cause
  551. // issues with mocking libraries. As such, we can only reload assemblies in the editor.
  552. return;
  553. }
  554. print_verbose(".NET: Reloading assemblies...");
  555. // There is no soft reloading with Mono. It's always hard reloading.
  556. List<Ref<CSharpScript>> scripts;
  557. {
  558. MutexLock lock(script_instances_mutex);
  559. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  560. // Do not reload scripts with only non-collectible instances to avoid disrupting event subscriptions and such.
  561. bool is_reloadable = elem->self()->instances.size() == 0;
  562. for (Object *obj : elem->self()->instances) {
  563. ERR_CONTINUE(!obj->get_script_instance());
  564. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  565. if (GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(csi->get_gchandle_intptr())) {
  566. is_reloadable = true;
  567. break;
  568. }
  569. }
  570. if (is_reloadable) {
  571. // Cast to CSharpScript to avoid being erased by accident.
  572. scripts.push_back(Ref<CSharpScript>(elem->self()));
  573. }
  574. }
  575. }
  576. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  577. // Serialize managed callables
  578. {
  579. MutexLock lock(ManagedCallable::instances_mutex);
  580. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  581. ManagedCallable *managed_callable = elem->self();
  582. ERR_CONTINUE(managed_callable->delegate_handle.value == nullptr);
  583. if (!GDMonoCache::managed_callbacks.GCHandleBridge_GCHandleIsTargetCollectible(managed_callable->delegate_handle)) {
  584. continue;
  585. }
  586. Array serialized_data;
  587. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TrySerializeDelegateWithGCHandle(
  588. managed_callable->delegate_handle, &serialized_data);
  589. if (success) {
  590. ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
  591. } else if (OS::get_singleton()->is_stdout_verbose()) {
  592. OS::get_singleton()->print("Failed to serialize delegate\n");
  593. }
  594. }
  595. }
  596. List<Ref<CSharpScript>> to_reload;
  597. // We need to keep reference instances alive during reloading
  598. List<Ref<RefCounted>> rc_instances;
  599. for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  600. const CSharpScriptBinding &script_binding = E.value;
  601. RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner);
  602. if (rc) {
  603. rc_instances.push_back(Ref<RefCounted>(rc));
  604. }
  605. }
  606. // As scripts are going to be reloaded, must proceed without locking here
  607. for (Ref<CSharpScript> &scr : scripts) {
  608. // If someone removes a script from a node, deletes the script, builds, adds a script to the
  609. // same node, then builds again, the script might have no path and also no script_class. In
  610. // that case, we can't (and don't need to) reload it.
  611. if (scr->get_path().is_empty() && !scr->valid) {
  612. continue;
  613. }
  614. to_reload.push_back(scr);
  615. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  616. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  617. for (Object *obj : scr->instances) {
  618. scr->pending_reload_instances.insert(obj->get_instance_id());
  619. // Since this script instance wasn't a placeholder, add it to the list of placeholders
  620. // that will have to be eventually replaced with a script instance in case it turns into one.
  621. // This list is not cleared after the reload and the collected instances only leave
  622. // the list if the script is instantiated or if it was a tool script but becomes a
  623. // non-tool script in a rebuild.
  624. scr->pending_replace_placeholders.insert(obj->get_instance_id());
  625. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  626. if (rc) {
  627. rc_instances.push_back(Ref<RefCounted>(rc));
  628. }
  629. }
  630. #ifdef TOOLS_ENABLED
  631. for (PlaceHolderScriptInstance *instance : scr->placeholders) {
  632. Object *obj = instance->get_owner();
  633. scr->pending_reload_instances.insert(obj->get_instance_id());
  634. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  635. if (rc) {
  636. rc_instances.push_back(Ref<RefCounted>(rc));
  637. }
  638. }
  639. #endif
  640. // Save state and remove script from instances
  641. RBMap<ObjectID, CSharpScript::StateBackup> &owners_map = scr->pending_reload_state;
  642. for (Object *obj : scr->instances) {
  643. ERR_CONTINUE(!obj->get_script_instance());
  644. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  645. // Call OnBeforeSerialize and save instance info
  646. CSharpScript::StateBackup state;
  647. Dictionary properties;
  648. GDMonoCache::managed_callbacks.CSharpInstanceBridge_SerializeState(
  649. csi->get_gchandle_intptr(), &properties, &state.event_signals);
  650. for (const Variant *s = properties.next(nullptr); s != nullptr; s = properties.next(s)) {
  651. StringName name = *s;
  652. Variant value = properties[*s];
  653. state.properties.push_back(Pair<StringName, Variant>(name, value));
  654. }
  655. owners_map[obj->get_instance_id()] = state;
  656. }
  657. }
  658. // After the state of all instances is saved, clear scripts and script instances
  659. for (Ref<CSharpScript> &scr : scripts) {
  660. while (scr->instances.begin()) {
  661. Object *obj = *scr->instances.begin();
  662. obj->set_script(Ref<RefCounted>()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  663. }
  664. scr->was_tool_before_reload = scr->type_info.is_tool;
  665. scr->_clear();
  666. }
  667. // Release the delegates that were serialized earlier.
  668. {
  669. MutexLock lock(ManagedCallable::instances_mutex);
  670. for (KeyValue<ManagedCallable *, Array> &kv : ManagedCallable::instances_pending_reload) {
  671. kv.key->release_delegate_handle();
  672. }
  673. }
  674. // Do domain reload
  675. if (gdmono->reload_project_assemblies() != OK) {
  676. // Failed to reload the scripts domain
  677. // Make sure to add the scripts back to their owners before returning
  678. for (Ref<CSharpScript> &scr : to_reload) {
  679. for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) {
  680. Object *obj = ObjectDB::get_instance(F.key);
  681. if (!obj) {
  682. continue;
  683. }
  684. ObjectID obj_id = obj->get_instance_id();
  685. // Use a placeholder for now to avoid losing the state when saving a scene
  686. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  687. obj->set_script_instance(placeholder);
  688. #ifdef TOOLS_ENABLED
  689. // Even though build didn't fail, this tells the placeholder to keep properties and
  690. // it allows using property_set_fallback for restoring the state without a valid script.
  691. scr->placeholder_fallback_enabled = true;
  692. #endif
  693. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  694. for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) {
  695. placeholder->property_set_fallback(G.first, G.second, nullptr);
  696. }
  697. scr->pending_reload_state.erase(obj_id);
  698. }
  699. scr->pending_reload_instances.clear();
  700. scr->pending_reload_state.clear();
  701. }
  702. return;
  703. }
  704. List<Ref<CSharpScript>> to_reload_state;
  705. for (Ref<CSharpScript> &scr : to_reload) {
  706. #ifdef TOOLS_ENABLED
  707. scr->exports_invalidated = true;
  708. #endif
  709. if (!scr->get_path().is_empty() && !scr->get_path().begins_with("csharp://")) {
  710. scr->reload(p_soft_reload);
  711. if (!scr->valid) {
  712. scr->pending_reload_instances.clear();
  713. scr->pending_reload_state.clear();
  714. continue;
  715. }
  716. } else {
  717. bool success = GDMonoCache::managed_callbacks.ScriptManagerBridge_TryReloadRegisteredScriptWithClass(scr.ptr());
  718. if (!success) {
  719. // Couldn't reload
  720. scr->pending_reload_instances.clear();
  721. scr->pending_reload_state.clear();
  722. continue;
  723. }
  724. }
  725. StringName native_name = scr->get_instance_base_type();
  726. {
  727. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  728. Object *obj = ObjectDB::get_instance(obj_id);
  729. if (!obj) {
  730. scr->pending_reload_state.erase(obj_id);
  731. continue;
  732. }
  733. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  734. // No longer inherits the same compatible type, can't reload
  735. scr->pending_reload_state.erase(obj_id);
  736. continue;
  737. }
  738. ScriptInstance *si = obj->get_script_instance();
  739. // Check if the script must be instantiated or kept as a placeholder
  740. // when the script may not be a tool (see #65266)
  741. bool replace_placeholder = scr->pending_replace_placeholders.has(obj->get_instance_id());
  742. if (!scr->is_tool() && scr->was_tool_before_reload) {
  743. // The script was a tool before the rebuild so the removal was intentional.
  744. replace_placeholder = false;
  745. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  746. }
  747. #ifdef TOOLS_ENABLED
  748. if (si) {
  749. // If the script instance is not null, then it must be a placeholder.
  750. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  751. CRASH_COND(!si->is_placeholder());
  752. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  753. // Replace placeholder with a script instance.
  754. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  755. // Backup placeholder script instance state before replacing it with a script instance.
  756. si->get_property_state(state_backup.properties);
  757. ScriptInstance *instance = scr->instance_create(obj);
  758. if (instance) {
  759. scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  760. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  761. obj->set_script_instance(instance);
  762. }
  763. }
  764. continue;
  765. }
  766. #else
  767. CRASH_COND(si != nullptr);
  768. #endif
  769. // Re-create the script instance.
  770. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  771. // Create script instance or replace placeholder with a script instance.
  772. ScriptInstance *instance = scr->instance_create(obj);
  773. if (instance) {
  774. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  775. obj->set_script_instance(instance);
  776. continue;
  777. }
  778. }
  779. // The script instance could not be instantiated or wasn't in the list of placeholders to replace.
  780. obj->set_script(scr);
  781. #ifdef DEBUG_ENABLED
  782. // If we reached here, the instantiated script must be a placeholder.
  783. CRASH_COND(!obj->get_script_instance()->is_placeholder());
  784. #endif
  785. }
  786. }
  787. to_reload_state.push_back(scr);
  788. }
  789. // Deserialize managed callables.
  790. // This is done before reloading script's internal state, so potential callables invoked in properties work.
  791. {
  792. MutexLock lock(ManagedCallable::instances_mutex);
  793. for (const KeyValue<ManagedCallable *, Array> &elem : ManagedCallable::instances_pending_reload) {
  794. ManagedCallable *managed_callable = elem.key;
  795. const Array &serialized_data = elem.value;
  796. GCHandleIntPtr delegate = { nullptr };
  797. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TryDeserializeDelegateWithGCHandle(
  798. &serialized_data, &delegate);
  799. if (success) {
  800. ERR_CONTINUE(delegate.value == nullptr);
  801. managed_callable->delegate_handle = delegate;
  802. } else if (OS::get_singleton()->is_stdout_verbose()) {
  803. OS::get_singleton()->print("Failed to deserialize delegate\n");
  804. }
  805. }
  806. ManagedCallable::instances_pending_reload.clear();
  807. }
  808. for (Ref<CSharpScript> &scr : to_reload_state) {
  809. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  810. Object *obj = ObjectDB::get_instance(obj_id);
  811. if (!obj) {
  812. scr->pending_reload_state.erase(obj_id);
  813. continue;
  814. }
  815. ERR_CONTINUE(!obj->get_script_instance());
  816. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  817. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  818. if (csi) {
  819. Dictionary properties;
  820. for (const Pair<StringName, Variant> &G : state_backup.properties) {
  821. properties[G.first] = G.second;
  822. }
  823. // Restore serialized state and call OnAfterDeserialize.
  824. GDMonoCache::managed_callbacks.CSharpInstanceBridge_DeserializeState(
  825. csi->get_gchandle_intptr(), &properties, &state_backup.event_signals);
  826. }
  827. }
  828. scr->pending_reload_instances.clear();
  829. scr->pending_reload_state.clear();
  830. }
  831. #ifdef TOOLS_ENABLED
  832. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  833. if (Engine::get_singleton()->is_editor_hint()) {
  834. InspectorDock::get_inspector_singleton()->update_tree();
  835. NodeDock::get_singleton()->update_lists();
  836. }
  837. #endif
  838. }
  839. #endif
  840. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  841. p_extensions->push_back("cs");
  842. }
  843. #ifdef TOOLS_ENABLED
  844. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  845. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  846. }
  847. bool CSharpLanguage::overrides_external_editor() {
  848. return get_godotsharp_editor()->call("OverridesExternalEditor");
  849. }
  850. #endif
  851. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  852. // Not a parser error in our case, but it's still used for other type of errors
  853. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  854. _debug_parse_err_line = p_line;
  855. _debug_parse_err_file = p_file;
  856. _debug_error = p_error;
  857. EngineDebugger::get_script_debugger()->debug(this, false, true);
  858. return true;
  859. } else {
  860. return false;
  861. }
  862. }
  863. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  864. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  865. _debug_parse_err_line = -1;
  866. _debug_parse_err_file = "";
  867. _debug_error = p_error;
  868. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue);
  869. return true;
  870. } else {
  871. return false;
  872. }
  873. }
  874. #ifdef TOOLS_ENABLED
  875. void CSharpLanguage::_editor_init_callback() {
  876. // Load GodotTools and initialize GodotSharpEditor
  877. int32_t interop_funcs_size = 0;
  878. const void **interop_funcs = godotsharp::get_editor_interop_funcs(interop_funcs_size);
  879. Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
  880. GodotSharpDirs::get_data_editor_tools_dir().path_join("GodotTools.dll").utf16(),
  881. interop_funcs, interop_funcs_size);
  882. CRASH_COND(editor_plugin_obj == nullptr);
  883. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);
  884. CRASH_COND(godotsharp_editor == nullptr);
  885. // Add plugin to EditorNode and enable it
  886. EditorNode::add_editor_plugin(godotsharp_editor);
  887. godotsharp_editor->enable_plugin();
  888. get_singleton()->godotsharp_editor = godotsharp_editor;
  889. }
  890. #endif
  891. void CSharpLanguage::set_language_index(int p_idx) {
  892. ERR_FAIL_COND(lang_idx != -1);
  893. lang_idx = p_idx;
  894. }
  895. void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
  896. if (!p_gchandle.is_released()) { // Do not lock unnecessarily
  897. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  898. p_gchandle.release();
  899. }
  900. }
  901. void CSharpLanguage::release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle) {
  902. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  903. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  904. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) {
  905. r_gchandle.release();
  906. }
  907. }
  908. }
  909. void CSharpLanguage::release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding) {
  910. MonoGCHandleData &gchandle = r_script_binding.gchandle;
  911. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  912. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  913. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) {
  914. gchandle.release();
  915. r_script_binding.inited = false; // Here too, to be thread safe
  916. }
  917. }
  918. }
  919. CSharpLanguage::CSharpLanguage() {
  920. ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
  921. singleton = this;
  922. }
  923. CSharpLanguage::~CSharpLanguage() {
  924. finalize();
  925. singleton = nullptr;
  926. }
  927. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  928. #ifdef DEBUG_ENABLED
  929. // I don't trust you
  930. if (p_object->get_script_instance()) {
  931. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  932. CRASH_COND(csharp_instance != nullptr && !csharp_instance->is_destructing_script_instance());
  933. }
  934. #endif
  935. StringName type_name = p_object->get_class_name();
  936. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  937. // This skipping of GDExtension classes, as well as whatever classes are in this list of ignored types, is a
  938. // workaround to allow GDExtension classes to be used from C# so long as they're only used through base classes that
  939. // are registered from the engine. This will likely need to be removed whenever proper support for GDExtension
  940. // classes is added to C#. See #75955 for more details.
  941. while (classinfo && (!classinfo->exposed || classinfo->gdextension || ignored_types.has(classinfo->name))) {
  942. classinfo = classinfo->inherits_ptr;
  943. }
  944. ERR_FAIL_NULL_V(classinfo, false);
  945. type_name = classinfo->name;
  946. bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), type_name);
  947. ERR_FAIL_COND_V_MSG(!parent_is_object_class, false,
  948. "Type inherits from native type '" + type_name + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
  949. #ifdef DEBUG_ENABLED
  950. CRASH_COND(!r_script_binding.gchandle.is_released());
  951. #endif
  952. GCHandleIntPtr strong_gchandle =
  953. GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(
  954. &type_name, p_object);
  955. ERR_FAIL_NULL_V(strong_gchandle.value, false);
  956. r_script_binding.inited = true;
  957. r_script_binding.type_name = type_name;
  958. r_script_binding.gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  959. r_script_binding.owner = p_object;
  960. // Tie managed to unmanaged
  961. RefCounted *rc = Object::cast_to<RefCounted>(p_object);
  962. if (rc) {
  963. // Unsafe refcount increment. The managed instance also counts as a reference.
  964. // This way if the unmanaged world has no references to our owner
  965. // but the managed instance is alive, the refcount will be 1 instead of 0.
  966. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  967. rc->reference();
  968. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  969. }
  970. return true;
  971. }
  972. RBMap<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  973. return script_bindings.insert(p_object, p_script_binding);
  974. }
  975. void *CSharpLanguage::_instance_binding_create_callback(void *, void *p_instance) {
  976. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  977. MutexLock lock(csharp_lang->language_bind_mutex);
  978. RBMap<Object *, CSharpScriptBinding>::Element *match = csharp_lang->script_bindings.find((Object *)p_instance);
  979. if (match) {
  980. return (void *)match;
  981. }
  982. CSharpScriptBinding script_binding;
  983. return (void *)csharp_lang->insert_script_binding((Object *)p_instance, script_binding);
  984. }
  985. void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_binding) {
  986. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  987. if (GDMono::get_singleton() == nullptr) {
  988. #ifdef DEBUG_ENABLED
  989. CRASH_COND(csharp_lang && !csharp_lang->script_bindings.is_empty());
  990. #endif
  991. // Mono runtime finalized, all the gchandle bindings were already released
  992. return;
  993. }
  994. if (csharp_lang->finalizing) {
  995. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  996. }
  997. {
  998. MutexLock lock(csharp_lang->language_bind_mutex);
  999. RBMap<Object *, CSharpScriptBinding>::Element *data = (RBMap<Object *, CSharpScriptBinding>::Element *)p_binding;
  1000. CSharpScriptBinding &script_binding = data->value();
  1001. if (script_binding.inited) {
  1002. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1003. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1004. GDMonoCache::managed_callbacks.ScriptManagerBridge_SetGodotObjectPtr(
  1005. script_binding.gchandle.get_intptr(), nullptr);
  1006. script_binding.gchandle.release();
  1007. script_binding.inited = false;
  1008. }
  1009. csharp_lang->script_bindings.erase(data);
  1010. }
  1011. }
  1012. GDExtensionBool CSharpLanguage::_instance_binding_reference_callback(void *p_token, void *p_binding, GDExtensionBool p_reference) {
  1013. // Instance bindings callbacks can only be called if the C# language is available.
  1014. // Failing this assert usually means that we didn't clear the instance binding in some Object
  1015. // and the C# language has already been finalized.
  1016. DEV_ASSERT(CSharpLanguage::get_singleton() != nullptr);
  1017. CRASH_COND(!p_binding);
  1018. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)p_binding)->get();
  1019. RefCounted *rc_owner = Object::cast_to<RefCounted>(script_binding.owner);
  1020. #ifdef DEBUG_ENABLED
  1021. CRASH_COND(!rc_owner);
  1022. #endif
  1023. MonoGCHandleData &gchandle = script_binding.gchandle;
  1024. int refcount = rc_owner->get_reference_count();
  1025. if (!script_binding.inited) {
  1026. return refcount == 0;
  1027. }
  1028. if (p_reference) {
  1029. // Refcount incremented
  1030. if (refcount > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1031. // The reference count was increased after the managed side was the only one referencing our owner.
  1032. // This means the owner is being referenced again by the unmanaged side,
  1033. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1034. // Release the current weak handle and replace it with a strong handle.
  1035. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1036. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1037. GCHandleIntPtr new_gchandle = { nullptr };
  1038. bool create_weak = false;
  1039. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1040. old_gchandle, &new_gchandle, create_weak);
  1041. if (!target_alive) {
  1042. return false; // Called after the managed side was collected, so nothing to do here
  1043. }
  1044. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1045. }
  1046. return false;
  1047. } else {
  1048. // Refcount decremented
  1049. if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1050. // If owner owner is no longer referenced by the unmanaged side,
  1051. // the managed instance takes responsibility of deleting the owner when GCed.
  1052. // Release the current strong handle and replace it with a weak handle.
  1053. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1054. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1055. GCHandleIntPtr new_gchandle = { nullptr };
  1056. bool create_weak = true;
  1057. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1058. old_gchandle, &new_gchandle, create_weak);
  1059. if (!target_alive) {
  1060. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1061. }
  1062. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1063. return false;
  1064. }
  1065. return refcount == 0;
  1066. }
  1067. }
  1068. void *CSharpLanguage::get_instance_binding(Object *p_object) {
  1069. return p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1070. }
  1071. void *CSharpLanguage::get_instance_binding_with_setup(Object *p_object) {
  1072. void *binding = get_instance_binding(p_object);
  1073. // Initially this was in `_instance_binding_create_callback`. However, after the new instance
  1074. // binding re-write it was resulting in a deadlock in `_instance_binding_reference`, as
  1075. // `setup_csharp_script_binding` may call `reference()`. It was moved here outside to fix that.
  1076. if (binding) {
  1077. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1078. if (!script_binding.inited) {
  1079. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1080. if (!script_binding.inited) { // Another thread may have set it up
  1081. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, p_object);
  1082. }
  1083. }
  1084. }
  1085. return binding;
  1086. }
  1087. void *CSharpLanguage::get_existing_instance_binding(Object *p_object) {
  1088. #ifdef DEBUG_ENABLED
  1089. CRASH_COND(p_object->has_instance_binding(p_object));
  1090. #endif
  1091. return get_instance_binding(p_object);
  1092. }
  1093. bool CSharpLanguage::has_instance_binding(Object *p_object) {
  1094. return p_object->has_instance_binding(get_singleton());
  1095. }
  1096. void CSharpLanguage::tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
  1097. // This method should not fail
  1098. CRASH_COND(!p_unmanaged);
  1099. // All mono objects created from the managed world (e.g.: 'new Player()')
  1100. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1101. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1102. CRASH_COND(p_ref_counted != (bool)rc);
  1103. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1104. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1105. // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
  1106. // script binding instead. One of the advantages of this is that if a script is attached
  1107. // later and it's not a C# script, then the managed object won't have to be disposed.
  1108. // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
  1109. // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
  1110. if (p_ref_counted) {
  1111. // Unsafe refcount increment. The managed instance also counts as a reference.
  1112. // This way if the unmanaged world has no references to our owner
  1113. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1114. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1115. // May not me referenced yet, so we must use init_ref() instead of reference()
  1116. if (rc->init_ref()) {
  1117. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1118. }
  1119. }
  1120. // The object was just created, no script instance binding should have been attached
  1121. CRASH_COND(CSharpLanguage::has_instance_binding(p_unmanaged));
  1122. void *binding = CSharpLanguage::get_singleton()->get_instance_binding(p_unmanaged);
  1123. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1124. script_binding.inited = true;
  1125. script_binding.type_name = *p_native_name;
  1126. script_binding.gchandle = gchandle;
  1127. script_binding.owner = p_unmanaged;
  1128. }
  1129. void CSharpLanguage::tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
  1130. // This method should not fail
  1131. Ref<CSharpScript> script = *p_script;
  1132. // We take care of destructing this reference here, so the managed code won't need to do another P/Invoke call
  1133. p_script->~Ref();
  1134. CRASH_COND(!p_unmanaged);
  1135. // All mono objects created from the managed world (e.g.: 'new Player()')
  1136. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1137. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1138. CRASH_COND(p_ref_counted != (bool)rc);
  1139. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1140. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1141. CRASH_COND(script.is_null());
  1142. CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(p_unmanaged, script.ptr(), gchandle);
  1143. p_unmanaged->set_script_and_instance(script, csharp_instance);
  1144. csharp_instance->connect_event_signals();
  1145. }
  1146. void CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
  1147. // This method should not fail
  1148. CRASH_COND(!p_unmanaged);
  1149. CSharpInstance *instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
  1150. if (!instance) {
  1151. // Native bindings don't need post-setup
  1152. return;
  1153. }
  1154. CRASH_COND(!instance->gchandle.is_released());
  1155. // Tie managed to unmanaged
  1156. instance->gchandle = MonoGCHandleData(p_gchandle_intptr, gdmono::GCHandleType::STRONG_HANDLE);
  1157. if (instance->base_ref_counted) {
  1158. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1159. }
  1160. {
  1161. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1162. // instances is a set, so it's safe to insert multiple times (e.g.: from _internal_new_managed)
  1163. instance->script->instances.insert(instance->owner);
  1164. }
  1165. instance->connect_event_signals();
  1166. }
  1167. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
  1168. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
  1169. RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
  1170. instance->base_ref_counted = rc != nullptr;
  1171. instance->owner = p_owner;
  1172. instance->gchandle = p_gchandle;
  1173. if (instance->base_ref_counted) {
  1174. instance->_reference_owner_unsafe();
  1175. }
  1176. {
  1177. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1178. p_script->instances.insert(p_owner);
  1179. }
  1180. return instance;
  1181. }
  1182. Object *CSharpInstance::get_owner() {
  1183. return owner;
  1184. }
  1185. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1186. ERR_FAIL_COND_V(!script.is_valid(), false);
  1187. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_Set(
  1188. gchandle.get_intptr(), &p_name, &p_value);
  1189. }
  1190. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1191. ERR_FAIL_COND_V(!script.is_valid(), false);
  1192. Variant ret_value;
  1193. bool ret = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Get(
  1194. gchandle.get_intptr(), &p_name, &ret_value);
  1195. if (ret) {
  1196. r_ret = ret_value;
  1197. return true;
  1198. }
  1199. return false;
  1200. }
  1201. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1202. List<PropertyInfo> props;
  1203. ERR_FAIL_COND(!script.is_valid());
  1204. #ifdef TOOLS_ENABLED
  1205. for (const PropertyInfo &prop : script->exported_members_cache) {
  1206. props.push_back(prop);
  1207. }
  1208. #else
  1209. for (const KeyValue<StringName, PropertyInfo> &E : script->member_info) {
  1210. props.push_front(E.value);
  1211. }
  1212. #endif
  1213. for (PropertyInfo &prop : props) {
  1214. validate_property(prop);
  1215. p_properties->push_back(prop);
  1216. }
  1217. // Call _get_property_list
  1218. StringName method = SNAME("_get_property_list");
  1219. Variant ret;
  1220. Callable::CallError call_error;
  1221. bool ok = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1222. gchandle.get_intptr(), &method, nullptr, 0, &call_error, &ret);
  1223. // CALL_ERROR_INVALID_METHOD would simply mean it was not overridden
  1224. if (call_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) {
  1225. if (call_error.error != Callable::CallError::CALL_OK) {
  1226. ERR_PRINT("Error calling '_get_property_list': " + Variant::get_call_error_text(method, nullptr, 0, call_error));
  1227. } else if (!ok) {
  1228. ERR_PRINT("Unexpected error calling '_get_property_list'");
  1229. } else {
  1230. Array array = ret;
  1231. for (int i = 0, size = array.size(); i < size; i++) {
  1232. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1233. }
  1234. }
  1235. }
  1236. CSharpScript *top = script.ptr()->base_script.ptr();
  1237. while (top != nullptr) {
  1238. props.clear();
  1239. #ifdef TOOLS_ENABLED
  1240. for (const PropertyInfo &prop : top->exported_members_cache) {
  1241. props.push_back(prop);
  1242. }
  1243. #else
  1244. for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
  1245. props.push_front(E.value);
  1246. }
  1247. #endif
  1248. for (PropertyInfo &prop : props) {
  1249. validate_property(prop);
  1250. p_properties->push_back(prop);
  1251. }
  1252. top = top->base_script.ptr();
  1253. }
  1254. }
  1255. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1256. if (script->member_info.has(p_name)) {
  1257. if (r_is_valid) {
  1258. *r_is_valid = true;
  1259. }
  1260. return script->member_info[p_name].type;
  1261. }
  1262. if (r_is_valid) {
  1263. *r_is_valid = false;
  1264. }
  1265. return Variant::NIL;
  1266. }
  1267. bool CSharpInstance::property_can_revert(const StringName &p_name) const {
  1268. ERR_FAIL_COND_V(!script.is_valid(), false);
  1269. Variant name_arg = p_name;
  1270. const Variant *args[1] = { &name_arg };
  1271. Variant ret;
  1272. Callable::CallError call_error;
  1273. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1274. gchandle.get_intptr(), &SNAME("_property_can_revert"), args, 1, &call_error, &ret);
  1275. if (call_error.error != Callable::CallError::CALL_OK) {
  1276. return false;
  1277. }
  1278. return (bool)ret;
  1279. }
  1280. void CSharpInstance::validate_property(PropertyInfo &p_property) const {
  1281. ERR_FAIL_COND(!script.is_valid());
  1282. Variant property_arg = (Dictionary)p_property;
  1283. const Variant *args[1] = { &property_arg };
  1284. Variant ret;
  1285. Callable::CallError call_error;
  1286. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1287. gchandle.get_intptr(), &SNAME("_validate_property"), args, 1, &call_error, &ret);
  1288. if (call_error.error != Callable::CallError::CALL_OK) {
  1289. return;
  1290. }
  1291. p_property = PropertyInfo::from_dict(property_arg);
  1292. }
  1293. bool CSharpInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
  1294. ERR_FAIL_COND_V(!script.is_valid(), false);
  1295. Variant name_arg = p_name;
  1296. const Variant *args[1] = { &name_arg };
  1297. Variant ret;
  1298. Callable::CallError call_error;
  1299. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1300. gchandle.get_intptr(), &SNAME("_property_get_revert"), args, 1, &call_error, &ret);
  1301. if (call_error.error != Callable::CallError::CALL_OK) {
  1302. return false;
  1303. }
  1304. r_ret = ret;
  1305. return true;
  1306. }
  1307. void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
  1308. if (!script->is_valid() || !script->valid) {
  1309. return;
  1310. }
  1311. script->get_script_method_list(p_list);
  1312. }
  1313. bool CSharpInstance::has_method(const StringName &p_method) const {
  1314. if (!script.is_valid()) {
  1315. return false;
  1316. }
  1317. if (!GDMonoCache::godot_api_cache_updated) {
  1318. return false;
  1319. }
  1320. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_HasMethodUnknownParams(
  1321. gchandle.get_intptr(), &p_method);
  1322. }
  1323. int CSharpInstance::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  1324. if (!script->is_valid() || !script->valid) {
  1325. if (r_is_valid) {
  1326. *r_is_valid = false;
  1327. }
  1328. return 0;
  1329. }
  1330. const CSharpScript *top = script.ptr();
  1331. while (top != nullptr) {
  1332. for (const CSharpScript::CSharpMethodInfo &E : top->methods) {
  1333. if (E.name == p_method) {
  1334. if (r_is_valid) {
  1335. *r_is_valid = true;
  1336. }
  1337. return E.method_info.arguments.size();
  1338. }
  1339. }
  1340. top = top->base_script.ptr();
  1341. }
  1342. if (r_is_valid) {
  1343. *r_is_valid = false;
  1344. }
  1345. return 0;
  1346. }
  1347. Variant CSharpInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1348. ERR_FAIL_COND_V(!script.is_valid(), Variant());
  1349. Variant ret;
  1350. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1351. gchandle.get_intptr(), &p_method, p_args, p_argcount, &r_error, &ret);
  1352. return ret;
  1353. }
  1354. bool CSharpInstance::_reference_owner_unsafe() {
  1355. #ifdef DEBUG_ENABLED
  1356. CRASH_COND(!base_ref_counted);
  1357. CRASH_COND(owner == nullptr);
  1358. CRASH_COND(unsafe_referenced); // already referenced
  1359. #endif
  1360. // Unsafe refcount increment. The managed instance also counts as a reference.
  1361. // This way if the unmanaged world has no references to our owner
  1362. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1363. // See: _unreference_owner_unsafe()
  1364. // May not be referenced yet, so we must use init_ref() instead of reference()
  1365. if (static_cast<RefCounted *>(owner)->init_ref()) {
  1366. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1367. unsafe_referenced = true;
  1368. }
  1369. return unsafe_referenced;
  1370. }
  1371. bool CSharpInstance::_unreference_owner_unsafe() {
  1372. #ifdef DEBUG_ENABLED
  1373. CRASH_COND(!base_ref_counted);
  1374. CRASH_COND(owner == nullptr);
  1375. #endif
  1376. if (!unsafe_referenced) {
  1377. return false; // Already unreferenced
  1378. }
  1379. unsafe_referenced = false;
  1380. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1381. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1382. // See: _reference_owner_unsafe()
  1383. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1384. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1385. return static_cast<RefCounted *>(owner)->unreference();
  1386. }
  1387. bool CSharpInstance::_internal_new_managed() {
  1388. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1389. ERR_FAIL_NULL_V(owner, false);
  1390. ERR_FAIL_COND_V(script.is_null(), false);
  1391. ERR_FAIL_COND_V(!script->can_instantiate(), false);
  1392. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1393. script.ptr(), owner, nullptr, 0);
  1394. if (!ok) {
  1395. // Important to clear this before destroying the script instance here
  1396. script = Ref<CSharpScript>();
  1397. owner = nullptr;
  1398. return false;
  1399. }
  1400. CRASH_COND(gchandle.is_released());
  1401. return true;
  1402. }
  1403. void CSharpInstance::mono_object_disposed(GCHandleIntPtr p_gchandle_to_free) {
  1404. // Must make sure event signals are not left dangling
  1405. disconnect_event_signals();
  1406. #ifdef DEBUG_ENABLED
  1407. CRASH_COND(base_ref_counted);
  1408. CRASH_COND(gchandle.is_released());
  1409. #endif
  1410. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1411. }
  1412. void CSharpInstance::mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1413. #ifdef DEBUG_ENABLED
  1414. CRASH_COND(!base_ref_counted);
  1415. CRASH_COND(gchandle.is_released());
  1416. #endif
  1417. // Must make sure event signals are not left dangling
  1418. disconnect_event_signals();
  1419. r_remove_script_instance = false;
  1420. if (_unreference_owner_unsafe()) {
  1421. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1422. r_delete_owner = true;
  1423. } else {
  1424. r_delete_owner = false;
  1425. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1426. if (!p_is_finalizer) {
  1427. // If the native instance is still alive and Dispose() was called
  1428. // (instead of the finalizer), then we remove the script instance.
  1429. r_remove_script_instance = true;
  1430. // TODO: Last usage of 'is_finalizing_scripts_domain'. It should be replaced with a check to determine if the load context is being unloaded.
  1431. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1432. // If the native instance is still alive and this is called from the finalizer,
  1433. // then it was referenced from another thread before the finalizer could
  1434. // unreference and delete it, so we want to keep it.
  1435. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1436. // could have already been collected. Instead we will create a new managed instance here.
  1437. if (!_internal_new_managed()) {
  1438. r_remove_script_instance = true;
  1439. }
  1440. }
  1441. }
  1442. }
  1443. void CSharpInstance::connect_event_signals() {
  1444. const CSharpScript *top = script.ptr();
  1445. while (top != nullptr && top->valid) {
  1446. for (const CSharpScript::EventSignalInfo &signal : top->event_signals) {
  1447. String signal_name = signal.name;
  1448. // TODO: Use pooling for ManagedCallable instances.
  1449. EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, signal_name));
  1450. Callable callable(event_signal_callable);
  1451. connected_event_signals.push_back(callable);
  1452. owner->connect(signal_name, callable);
  1453. }
  1454. top = top->base_script.ptr();
  1455. }
  1456. }
  1457. void CSharpInstance::disconnect_event_signals() {
  1458. for (const Callable &callable : connected_event_signals) {
  1459. const EventSignalCallable *event_signal_callable = static_cast<const EventSignalCallable *>(callable.get_custom());
  1460. owner->disconnect(event_signal_callable->get_signal(), callable);
  1461. }
  1462. connected_event_signals.clear();
  1463. }
  1464. void CSharpInstance::refcount_incremented() {
  1465. #ifdef DEBUG_ENABLED
  1466. CRASH_COND(!base_ref_counted);
  1467. CRASH_COND(owner == nullptr);
  1468. #endif
  1469. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1470. if (rc_owner->get_reference_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1471. // The reference count was increased after the managed side was the only one referencing our owner.
  1472. // This means the owner is being referenced again by the unmanaged side,
  1473. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1474. // Release the current weak handle and replace it with a strong handle.
  1475. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1476. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1477. GCHandleIntPtr new_gchandle = { nullptr };
  1478. bool create_weak = false;
  1479. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1480. old_gchandle, &new_gchandle, create_weak);
  1481. if (!target_alive) {
  1482. return; // Called after the managed side was collected, so nothing to do here
  1483. }
  1484. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1485. }
  1486. }
  1487. bool CSharpInstance::refcount_decremented() {
  1488. #ifdef DEBUG_ENABLED
  1489. CRASH_COND(!base_ref_counted);
  1490. CRASH_COND(owner == nullptr);
  1491. #endif
  1492. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1493. int refcount = rc_owner->get_reference_count();
  1494. if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1495. // If owner owner is no longer referenced by the unmanaged side,
  1496. // the managed instance takes responsibility of deleting the owner when GCed.
  1497. // Release the current strong handle and replace it with a weak handle.
  1498. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1499. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1500. GCHandleIntPtr new_gchandle = { nullptr };
  1501. bool create_weak = true;
  1502. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1503. old_gchandle, &new_gchandle, create_weak);
  1504. if (!target_alive) {
  1505. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1506. }
  1507. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1508. return false;
  1509. }
  1510. ref_dying = (refcount == 0);
  1511. return ref_dying;
  1512. }
  1513. const Variant CSharpInstance::get_rpc_config() const {
  1514. return script->get_rpc_config();
  1515. }
  1516. void CSharpInstance::notification(int p_notification, bool p_reversed) {
  1517. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1518. if (base_ref_counted) {
  1519. // At this point, Dispose() was already called (manually or from the finalizer).
  1520. // The RefCounted wouldn't have reached 0 otherwise, since the managed side
  1521. // references it and Dispose() needs to be called to release it.
  1522. // However, this means C# RefCounted scripts can't receive NOTIFICATION_PREDELETE, but
  1523. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1524. return;
  1525. }
  1526. } else if (p_notification == Object::NOTIFICATION_PREDELETE_CLEANUP) {
  1527. // When NOTIFICATION_PREDELETE_CLEANUP is sent, we also take the chance to call Dispose().
  1528. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE_CLEANUP is guaranteed
  1529. // to be sent at least once, which happens right before the call to the destructor.
  1530. predelete_notified = true;
  1531. if (base_ref_counted) {
  1532. // At this point, Dispose() was already called (manually or from the finalizer).
  1533. // The RefCounted wouldn't have reached 0 otherwise, since the managed side
  1534. // references it and Dispose() needs to be called to release it.
  1535. return;
  1536. }
  1537. // NOTIFICATION_PREDELETE_CLEANUP is not sent to scripts.
  1538. // After calling Dispose() the C# instance can no longer be used,
  1539. // so it should be the last thing we do.
  1540. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1541. gchandle.get_intptr(), /* okIfNull */ false);
  1542. return;
  1543. }
  1544. _call_notification(p_notification, p_reversed);
  1545. }
  1546. void CSharpInstance::_call_notification(int p_notification, bool p_reversed) {
  1547. Variant arg = p_notification;
  1548. const Variant *args[1] = { &arg };
  1549. Variant ret;
  1550. Callable::CallError call_error;
  1551. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1552. gchandle.get_intptr(), &SNAME("_notification"), args, 1, &call_error, &ret);
  1553. }
  1554. String CSharpInstance::to_string(bool *r_valid) {
  1555. String res;
  1556. bool valid;
  1557. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallToString(
  1558. gchandle.get_intptr(), &res, &valid);
  1559. if (r_valid) {
  1560. *r_valid = valid;
  1561. }
  1562. return res;
  1563. }
  1564. Ref<Script> CSharpInstance::get_script() const {
  1565. return script;
  1566. }
  1567. ScriptLanguage *CSharpInstance::get_language() {
  1568. return CSharpLanguage::get_singleton();
  1569. }
  1570. CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
  1571. script(p_script) {
  1572. }
  1573. CSharpInstance::~CSharpInstance() {
  1574. destructing_script_instance = true;
  1575. // Must make sure event signals are not left dangling
  1576. disconnect_event_signals();
  1577. if (!gchandle.is_released()) {
  1578. if (!predelete_notified && !ref_dying) {
  1579. // This destructor is not called from the owners destructor.
  1580. // This could be being called from the owner's set_script_instance method,
  1581. // meaning this script is being replaced with another one. If this is the case,
  1582. // we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
  1583. // and that would mess up with the new script instance if called later.
  1584. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1585. gchandle.get_intptr(), /* okIfNull */ true);
  1586. }
  1587. gchandle.release(); // Make sure the gchandle is released
  1588. }
  1589. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1590. if (base_ref_counted && !ref_dying && owner && unsafe_referenced) {
  1591. // The owner's script or script instance is being replaced (or removed)
  1592. // Transfer ownership to an "instance binding"
  1593. RefCounted *rc_owner = static_cast<RefCounted *>(owner);
  1594. // We will unreference the owner before referencing it again, so we need to keep it alive
  1595. Ref<RefCounted> scope_keep_owner_alive(rc_owner);
  1596. (void)scope_keep_owner_alive;
  1597. // Unreference the owner here, before the new "instance binding" references it.
  1598. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
  1599. bool die = _unreference_owner_unsafe();
  1600. CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
  1601. void *data = CSharpLanguage::get_instance_binding_with_setup(owner);
  1602. CRASH_COND(data == nullptr);
  1603. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1604. CRASH_COND(!script_binding.inited);
  1605. #ifdef DEBUG_ENABLED
  1606. // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
  1607. CRASH_COND(rc_owner->get_reference_count() <= 1);
  1608. #endif
  1609. }
  1610. if (script.is_valid() && owner) {
  1611. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1612. #ifdef DEBUG_ENABLED
  1613. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1614. HashSet<Object *>::Iterator match = script->instances.find(owner);
  1615. CRASH_COND(!match);
  1616. script->instances.remove(match);
  1617. #else
  1618. script->instances.erase(owner);
  1619. #endif
  1620. }
  1621. }
  1622. #ifdef TOOLS_ENABLED
  1623. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1624. placeholders.erase(p_placeholder);
  1625. }
  1626. #endif
  1627. #ifdef TOOLS_ENABLED
  1628. void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1629. for (const KeyValue<StringName, Variant> &E : exported_members_defval_cache) {
  1630. values[E.key] = E.value;
  1631. }
  1632. for (const PropertyInfo &prop_info : exported_members_cache) {
  1633. propnames.push_back(prop_info);
  1634. }
  1635. if (base_script.is_valid()) {
  1636. base_script->_update_exports_values(values, propnames);
  1637. }
  1638. }
  1639. #endif
  1640. void GD_CLR_STDCALL CSharpScript::_add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count) {
  1641. GDMonoCache::godotsharp_property_info *props = (GDMonoCache::godotsharp_property_info *)p_props;
  1642. #ifdef TOOLS_ENABLED
  1643. p_script->exported_members_cache.push_back(PropertyInfo(
  1644. Variant::NIL, p_script->type_info.class_name, PROPERTY_HINT_NONE,
  1645. p_script->get_path(), PROPERTY_USAGE_CATEGORY));
  1646. #endif
  1647. for (int i = 0; i < p_count; i++) {
  1648. const GDMonoCache::godotsharp_property_info &prop = props[i];
  1649. StringName name = *reinterpret_cast<const StringName *>(&prop.name);
  1650. String hint_string = *reinterpret_cast<const String *>(&prop.hint_string);
  1651. PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage);
  1652. p_script->member_info[name] = pinfo;
  1653. if (prop.exported) {
  1654. #ifdef TOOLS_ENABLED
  1655. p_script->exported_members_cache.push_back(pinfo);
  1656. #endif
  1657. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1658. p_script->exported_members_names.insert(name);
  1659. #endif
  1660. }
  1661. }
  1662. }
  1663. #ifdef TOOLS_ENABLED
  1664. void GD_CLR_STDCALL CSharpScript::_add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count) {
  1665. GDMonoCache::godotsharp_property_def_val_pair *def_vals = (GDMonoCache::godotsharp_property_def_val_pair *)p_def_vals;
  1666. for (int i = 0; i < p_count; i++) {
  1667. const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = def_vals[i];
  1668. StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name);
  1669. Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value);
  1670. p_script->exported_members_defval_cache[name] = value;
  1671. }
  1672. }
  1673. #endif
  1674. bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) {
  1675. #ifdef TOOLS_ENABLED
  1676. bool is_editor = Engine::get_singleton()->is_editor_hint();
  1677. if (is_editor) {
  1678. placeholder_fallback_enabled = true; // until proven otherwise
  1679. }
  1680. #endif
  1681. if (!valid) {
  1682. return false;
  1683. }
  1684. bool changed = false;
  1685. #ifdef TOOLS_ENABLED
  1686. if (exports_invalidated)
  1687. #endif
  1688. {
  1689. #ifdef TOOLS_ENABLED
  1690. exports_invalidated = false;
  1691. #endif
  1692. changed = true;
  1693. member_info.clear();
  1694. #ifdef TOOLS_ENABLED
  1695. exported_members_cache.clear();
  1696. exported_members_defval_cache.clear();
  1697. #endif
  1698. if (GDMonoCache::godot_api_cache_updated) {
  1699. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this, &_add_property_info_list_callback);
  1700. #ifdef TOOLS_ENABLED
  1701. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this, &_add_property_default_values_callback);
  1702. #endif
  1703. }
  1704. }
  1705. #ifdef TOOLS_ENABLED
  1706. if (is_editor) {
  1707. placeholder_fallback_enabled = false;
  1708. if ((changed || p_instance_to_update) && placeholders.size()) {
  1709. // Update placeholders if any
  1710. HashMap<StringName, Variant> values;
  1711. List<PropertyInfo> propnames;
  1712. _update_exports_values(values, propnames);
  1713. if (changed) {
  1714. for (PlaceHolderScriptInstance *instance : placeholders) {
  1715. instance->update(propnames, values);
  1716. }
  1717. } else {
  1718. p_instance_to_update->update(propnames, values);
  1719. }
  1720. } else if (placeholders.size()) {
  1721. uint64_t script_modified_time = FileAccess::get_modified_time(get_path());
  1722. uint64_t last_valid_build_time = GDMono::get_singleton()->get_project_assembly_modified_time();
  1723. if (script_modified_time > last_valid_build_time) {
  1724. for (PlaceHolderScriptInstance *instance : placeholders) {
  1725. Object *owner = instance->get_owner();
  1726. if (owner->get_script_instance() == instance) {
  1727. owner->notify_property_list_changed();
  1728. }
  1729. }
  1730. }
  1731. }
  1732. }
  1733. #endif
  1734. return changed;
  1735. }
  1736. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1737. if (p_name == SNAME("script/source")) {
  1738. r_ret = get_source_code();
  1739. return true;
  1740. }
  1741. return false;
  1742. }
  1743. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1744. if (p_name == SNAME("script/source")) {
  1745. set_source_code(p_value);
  1746. reload();
  1747. return true;
  1748. }
  1749. return false;
  1750. }
  1751. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1752. p_properties->push_back(PropertyInfo(Variant::STRING, SNAME("script/source"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
  1753. }
  1754. void CSharpScript::_bind_methods() {
  1755. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  1756. }
  1757. void CSharpScript::reload_registered_script(Ref<CSharpScript> p_script) {
  1758. // IMPORTANT:
  1759. // This method must be called only after the CSharpScript and its associated type
  1760. // have been added to the script bridge map in the ScriptManagerBridge C# class.
  1761. // Other than that, it's the same as `CSharpScript::reload`.
  1762. // This method should not fail, only assertions allowed.
  1763. // Unlike `reload`, we print an error rather than silently returning,
  1764. // as we can assert this won't be called a second time until invalidated.
  1765. ERR_FAIL_COND(!p_script->reload_invalidated);
  1766. p_script->valid = true;
  1767. p_script->reload_invalidated = false;
  1768. update_script_class_info(p_script);
  1769. p_script->_update_exports();
  1770. #ifdef TOOLS_ENABLED
  1771. // If the EditorFileSystem singleton is available, update the file;
  1772. // otherwise, the file will be updated when the singleton becomes available.
  1773. EditorFileSystem *efs = EditorFileSystem::get_singleton();
  1774. if (efs && !p_script->get_path().is_empty()) {
  1775. efs->update_file(p_script->get_path());
  1776. }
  1777. #endif
  1778. }
  1779. // Extract information about the script using the mono class.
  1780. void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
  1781. TypeInfo type_info;
  1782. // TODO: Use GDExtension godot_dictionary
  1783. Array methods_array;
  1784. methods_array.~Array();
  1785. Dictionary rpc_functions_dict;
  1786. rpc_functions_dict.~Dictionary();
  1787. Dictionary signals_dict;
  1788. signals_dict.~Dictionary();
  1789. Ref<CSharpScript> base_script;
  1790. GDMonoCache::managed_callbacks.ScriptManagerBridge_UpdateScriptClassInfo(
  1791. p_script.ptr(), &type_info,
  1792. &methods_array, &rpc_functions_dict, &signals_dict, &base_script);
  1793. p_script->type_info = type_info;
  1794. p_script->rpc_config.clear();
  1795. p_script->rpc_config = rpc_functions_dict;
  1796. // Methods
  1797. p_script->methods.clear();
  1798. p_script->methods.resize(methods_array.size());
  1799. int push_index = 0;
  1800. for (int i = 0; i < methods_array.size(); i++) {
  1801. Dictionary method_info_dict = methods_array[i];
  1802. StringName name = method_info_dict["name"];
  1803. MethodInfo mi;
  1804. mi.name = name;
  1805. mi.return_val = PropertyInfo::from_dict(method_info_dict["return_val"]);
  1806. Array params = method_info_dict["params"];
  1807. for (int j = 0; j < params.size(); j++) {
  1808. Dictionary param = params[j];
  1809. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1810. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1811. arg_info.usage = (uint32_t)param["usage"];
  1812. if (param.has("class_name")) {
  1813. arg_info.class_name = (StringName)param["class_name"];
  1814. }
  1815. mi.arguments.push_back(arg_info);
  1816. }
  1817. mi.flags = (uint32_t)method_info_dict["flags"];
  1818. p_script->methods.set(push_index++, CSharpMethodInfo{ name, mi });
  1819. }
  1820. // Event signals
  1821. // Performance is not critical here as this will be replaced with source generators.
  1822. p_script->event_signals.clear();
  1823. // Sigh... can't we just have capacity?
  1824. p_script->event_signals.resize(signals_dict.size());
  1825. push_index = 0;
  1826. for (const Variant *s = signals_dict.next(nullptr); s != nullptr; s = signals_dict.next(s)) {
  1827. StringName name = *s;
  1828. MethodInfo mi;
  1829. mi.name = name;
  1830. Array params = signals_dict[*s];
  1831. for (int i = 0; i < params.size(); i++) {
  1832. Dictionary param = params[i];
  1833. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1834. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1835. arg_info.usage = (uint32_t)param["usage"];
  1836. if (param.has("class_name")) {
  1837. arg_info.class_name = (StringName)param["class_name"];
  1838. }
  1839. mi.arguments.push_back(arg_info);
  1840. }
  1841. p_script->event_signals.set(push_index++, EventSignalInfo{ name, mi });
  1842. }
  1843. p_script->base_script = base_script;
  1844. }
  1845. bool CSharpScript::can_instantiate() const {
  1846. #ifdef TOOLS_ENABLED
  1847. bool extra_cond = type_info.is_tool || ScriptServer::is_scripting_enabled();
  1848. #else
  1849. bool extra_cond = true;
  1850. #endif
  1851. // FIXME Need to think this through better.
  1852. // For tool scripts, this will never fire if the class is not found. That's because we
  1853. // don't know if it's a tool script if we can't find the class to access the attributes.
  1854. if (extra_cond && !valid) {
  1855. ERR_FAIL_V_MSG(false, "Cannot instantiate C# script because the associated class could not be found. Script: '" + get_path() + "'. Make sure the script exists and contains a class definition with a name that matches the filename of the script exactly (it's case-sensitive).");
  1856. }
  1857. return valid && type_info.can_instantiate() && extra_cond;
  1858. }
  1859. StringName CSharpScript::get_instance_base_type() const {
  1860. StringName native_name;
  1861. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1862. return native_name;
  1863. }
  1864. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
  1865. ERR_FAIL_COND_V_MSG(!type_info.can_instantiate(), nullptr, "Cannot instantiate C# script. Script: '" + get_path() + "'.");
  1866. /* STEP 1, CREATE */
  1867. Ref<RefCounted> ref;
  1868. if (p_is_ref_counted) {
  1869. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  1870. ref = Ref<RefCounted>(static_cast<RefCounted *>(p_owner));
  1871. }
  1872. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  1873. if (CSharpLanguage::has_instance_binding(p_owner)) {
  1874. void *data = CSharpLanguage::get_existing_instance_binding(p_owner);
  1875. CRASH_COND(data == nullptr);
  1876. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1877. if (script_binding.inited && !script_binding.gchandle.is_released()) {
  1878. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1879. script_binding.gchandle.get_intptr(), /* okIfNull */ true);
  1880. script_binding.gchandle.release(); // Just in case
  1881. script_binding.inited = false;
  1882. }
  1883. }
  1884. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this)));
  1885. instance->base_ref_counted = p_is_ref_counted;
  1886. instance->owner = p_owner;
  1887. instance->owner->set_script_instance(instance);
  1888. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1889. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1890. this, p_owner, p_args, p_argcount);
  1891. if (!ok) {
  1892. // Important to clear this before destroying the script instance here
  1893. instance->script = Ref<CSharpScript>();
  1894. p_owner->set_script_instance(nullptr);
  1895. instance->owner = nullptr;
  1896. return nullptr;
  1897. }
  1898. CRASH_COND(instance->gchandle.is_released());
  1899. /* STEP 3, PARTY */
  1900. //@TODO make thread safe
  1901. return instance;
  1902. }
  1903. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1904. if (!valid) {
  1905. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1906. return Variant();
  1907. }
  1908. r_error.error = Callable::CallError::CALL_OK;
  1909. StringName native_name;
  1910. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1911. ERR_FAIL_COND_V(native_name == StringName(), Variant());
  1912. Object *owner = ClassDB::instantiate(native_name);
  1913. Ref<RefCounted> ref;
  1914. RefCounted *r = Object::cast_to<RefCounted>(owner);
  1915. if (r) {
  1916. ref = Ref<RefCounted>(r);
  1917. }
  1918. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
  1919. if (!instance) {
  1920. if (ref.is_null()) {
  1921. memdelete(owner); // no owner, sorry
  1922. }
  1923. return Variant();
  1924. }
  1925. if (ref.is_valid()) {
  1926. return ref;
  1927. } else {
  1928. return owner;
  1929. }
  1930. }
  1931. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1932. #ifdef DEBUG_ENABLED
  1933. CRASH_COND(!valid);
  1934. #endif
  1935. StringName native_name;
  1936. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1937. ERR_FAIL_COND_V(native_name == StringName(), nullptr);
  1938. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1939. if (EngineDebugger::is_active()) {
  1940. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
  1941. "Script inherits from native type '" + String(native_name) +
  1942. "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'");
  1943. }
  1944. ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'.");
  1945. }
  1946. Callable::CallError unchecked_error;
  1947. return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error);
  1948. }
  1949. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1950. #ifdef TOOLS_ENABLED
  1951. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1952. placeholders.insert(si);
  1953. _update_exports(si);
  1954. return si;
  1955. #else
  1956. return nullptr;
  1957. #endif
  1958. }
  1959. bool CSharpScript::instance_has(const Object *p_this) const {
  1960. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1961. return instances.has((Object *)p_this);
  1962. }
  1963. bool CSharpScript::has_source_code() const {
  1964. return !source.is_empty();
  1965. }
  1966. String CSharpScript::get_source_code() const {
  1967. return source;
  1968. }
  1969. void CSharpScript::set_source_code(const String &p_code) {
  1970. if (source == p_code) {
  1971. return;
  1972. }
  1973. source = p_code;
  1974. #ifdef TOOLS_ENABLED
  1975. source_changed_cache = true;
  1976. #endif
  1977. }
  1978. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  1979. if (!valid) {
  1980. return;
  1981. }
  1982. const CSharpScript *top = this;
  1983. while (top != nullptr) {
  1984. for (const CSharpMethodInfo &E : top->methods) {
  1985. p_list->push_back(E.method_info);
  1986. }
  1987. top = top->base_script.ptr();
  1988. }
  1989. }
  1990. bool CSharpScript::has_method(const StringName &p_method) const {
  1991. if (!valid) {
  1992. return false;
  1993. }
  1994. for (const CSharpMethodInfo &E : methods) {
  1995. if (E.name == p_method) {
  1996. return true;
  1997. }
  1998. }
  1999. return false;
  2000. }
  2001. int CSharpScript::get_script_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  2002. if (!valid) {
  2003. if (r_is_valid) {
  2004. *r_is_valid = false;
  2005. }
  2006. return 0;
  2007. }
  2008. for (const CSharpMethodInfo &E : methods) {
  2009. if (E.name == p_method) {
  2010. if (r_is_valid) {
  2011. *r_is_valid = true;
  2012. }
  2013. return E.method_info.arguments.size();
  2014. }
  2015. }
  2016. if (r_is_valid) {
  2017. *r_is_valid = false;
  2018. }
  2019. return 0;
  2020. }
  2021. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2022. if (!valid) {
  2023. return MethodInfo();
  2024. }
  2025. MethodInfo mi;
  2026. for (const CSharpMethodInfo &E : methods) {
  2027. if (E.name == p_method) {
  2028. if (mi.name == p_method) {
  2029. // We already found a method with the same name before so
  2030. // that means this method has overloads, the best we can do
  2031. // is return an empty MethodInfo.
  2032. return MethodInfo();
  2033. }
  2034. mi = E.method_info;
  2035. }
  2036. }
  2037. return mi;
  2038. }
  2039. Variant CSharpScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  2040. if (valid) {
  2041. Variant ret;
  2042. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CallStatic(this, &p_method, p_args, p_argcount, &r_error, &ret);
  2043. if (ok) {
  2044. return ret;
  2045. }
  2046. }
  2047. return Script::callp(p_method, p_args, p_argcount, r_error);
  2048. }
  2049. Error CSharpScript::reload(bool p_keep_state) {
  2050. if (!reload_invalidated) {
  2051. return OK;
  2052. }
  2053. // In the case of C#, reload doesn't really do any script reloading.
  2054. // That's done separately via domain reloading.
  2055. reload_invalidated = false;
  2056. String script_path = get_path();
  2057. valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(this, &script_path);
  2058. if (valid) {
  2059. #ifdef DEBUG_ENABLED
  2060. print_verbose("Found class for script " + get_path());
  2061. #endif
  2062. update_script_class_info(this);
  2063. _update_exports();
  2064. #ifdef TOOLS_ENABLED
  2065. // If the EditorFileSystem singleton is available, update the file;
  2066. // otherwise, the file will be updated when the singleton becomes available.
  2067. EditorFileSystem *efs = EditorFileSystem::get_singleton();
  2068. if (efs) {
  2069. efs->update_file(script_path);
  2070. }
  2071. #endif
  2072. }
  2073. return OK;
  2074. }
  2075. ScriptLanguage *CSharpScript::get_language() const {
  2076. return CSharpLanguage::get_singleton();
  2077. }
  2078. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2079. #ifdef TOOLS_ENABLED
  2080. HashMap<StringName, Variant>::ConstIterator E = exported_members_defval_cache.find(p_property);
  2081. if (E) {
  2082. r_value = E->value;
  2083. return true;
  2084. }
  2085. if (base_script.is_valid()) {
  2086. return base_script->get_property_default_value(p_property, r_value);
  2087. }
  2088. #endif
  2089. return false;
  2090. }
  2091. void CSharpScript::update_exports() {
  2092. #ifdef TOOLS_ENABLED
  2093. _update_exports();
  2094. #endif
  2095. }
  2096. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2097. if (!valid) {
  2098. return false;
  2099. }
  2100. if (!GDMonoCache::godot_api_cache_updated) {
  2101. return false;
  2102. }
  2103. for (const EventSignalInfo &signal : event_signals) {
  2104. if (signal.name == p_signal) {
  2105. return true;
  2106. }
  2107. }
  2108. if (base_script.is_valid()) {
  2109. return base_script->has_script_signal(p_signal);
  2110. }
  2111. return false;
  2112. }
  2113. void CSharpScript::_get_script_signal_list(List<MethodInfo> *r_signals, bool p_include_base) const {
  2114. if (!valid) {
  2115. return;
  2116. }
  2117. for (const EventSignalInfo &signal : event_signals) {
  2118. r_signals->push_back(signal.method_info);
  2119. }
  2120. if (!p_include_base) {
  2121. return;
  2122. }
  2123. if (base_script.is_valid()) {
  2124. base_script->get_script_signal_list(r_signals);
  2125. }
  2126. }
  2127. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2128. _get_script_signal_list(r_signals, true);
  2129. }
  2130. bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
  2131. Ref<CSharpScript> cs = p_script;
  2132. if (cs.is_null()) {
  2133. return false;
  2134. }
  2135. if (!valid || !cs->valid) {
  2136. return false;
  2137. }
  2138. if (!GDMonoCache::godot_api_cache_updated) {
  2139. return false;
  2140. }
  2141. return GDMonoCache::managed_callbacks.ScriptManagerBridge_ScriptIsOrInherits(this, cs.ptr());
  2142. }
  2143. Ref<Script> CSharpScript::get_base_script() const {
  2144. return base_script;
  2145. }
  2146. StringName CSharpScript::get_global_name() const {
  2147. return type_info.is_global_class ? StringName(type_info.class_name) : StringName();
  2148. }
  2149. void CSharpScript::get_script_property_list(List<PropertyInfo> *r_list) const {
  2150. #ifdef TOOLS_ENABLED
  2151. const CSharpScript *top = this;
  2152. while (top != nullptr) {
  2153. for (const PropertyInfo &E : top->exported_members_cache) {
  2154. r_list->push_back(E);
  2155. }
  2156. top = top->base_script.ptr();
  2157. }
  2158. #else
  2159. const CSharpScript *top = this;
  2160. while (top != nullptr) {
  2161. List<PropertyInfo> props;
  2162. for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
  2163. props.push_front(E.value);
  2164. }
  2165. for (const PropertyInfo &prop : props) {
  2166. r_list->push_back(prop);
  2167. }
  2168. top = top->base_script.ptr();
  2169. }
  2170. #endif
  2171. }
  2172. int CSharpScript::get_member_line(const StringName &p_member) const {
  2173. // TODO omnisharp
  2174. return -1;
  2175. }
  2176. Variant CSharpScript::get_rpc_config() const {
  2177. return rpc_config;
  2178. }
  2179. Error CSharpScript::load_source_code(const String &p_path) {
  2180. Error ferr = read_all_file_utf8(p_path, source);
  2181. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2182. ferr == ERR_INVALID_DATA
  2183. ? "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2184. " Please ensure that scripts are saved in valid UTF-8 unicode."
  2185. : "Failed to read file: '" + p_path + "'.");
  2186. #ifdef TOOLS_ENABLED
  2187. source_changed_cache = true;
  2188. #endif
  2189. return OK;
  2190. }
  2191. void CSharpScript::_clear() {
  2192. type_info = TypeInfo();
  2193. valid = false;
  2194. reload_invalidated = true;
  2195. }
  2196. CSharpScript::CSharpScript() {
  2197. _clear();
  2198. #ifdef DEBUG_ENABLED
  2199. {
  2200. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2201. CSharpLanguage::get_singleton()->script_list.add(&script_list);
  2202. }
  2203. #endif
  2204. }
  2205. CSharpScript::~CSharpScript() {
  2206. #ifdef DEBUG_ENABLED
  2207. {
  2208. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2209. CSharpLanguage::get_singleton()->script_list.remove(&script_list);
  2210. }
  2211. #endif
  2212. if (GDMonoCache::godot_api_cache_updated) {
  2213. GDMonoCache::managed_callbacks.ScriptManagerBridge_RemoveScriptBridge(this);
  2214. }
  2215. }
  2216. void CSharpScript::get_members(HashSet<StringName> *p_members) {
  2217. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  2218. if (p_members) {
  2219. for (const StringName &member_name : exported_members_names) {
  2220. p_members->insert(member_name);
  2221. }
  2222. }
  2223. #endif
  2224. }
  2225. /*************** RESOURCE ***************/
  2226. Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  2227. if (r_error) {
  2228. *r_error = ERR_FILE_CANT_OPEN;
  2229. }
  2230. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2231. String real_path = p_path;
  2232. if (p_path.begins_with("csharp://")) {
  2233. // This is a virtual path used by generic types, extract the real path.
  2234. real_path = "res://" + p_path.trim_prefix("csharp://");
  2235. real_path = real_path.substr(0, real_path.rfind_char(':'));
  2236. }
  2237. Ref<CSharpScript> scr;
  2238. if (GDMonoCache::godot_api_cache_updated) {
  2239. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetOrCreateScriptBridgeForPath(&p_path, &scr);
  2240. ERR_FAIL_COND_V_MSG(scr.is_null(), Ref<Resource>(), "Could not create C# script '" + real_path + "'.");
  2241. } else {
  2242. scr.instantiate();
  2243. }
  2244. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2245. Error err = scr->load_source_code(real_path);
  2246. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot load C# script file '" + real_path + "'.");
  2247. #endif
  2248. // Only one instance of a C# script is allowed to exist.
  2249. ERR_FAIL_COND_V_MSG(!scr->get_path().is_empty() && scr->get_path() != p_original_path, Ref<Resource>(),
  2250. "The C# script path is different from the path it was registered in the C# dictionary.");
  2251. Ref<Resource> existing = ResourceCache::get_ref(p_path);
  2252. switch (p_cache_mode) {
  2253. case ResourceFormatLoader::CACHE_MODE_IGNORE:
  2254. case ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP:
  2255. break;
  2256. case ResourceFormatLoader::CACHE_MODE_REUSE:
  2257. if (existing.is_null()) {
  2258. scr->set_path(p_original_path);
  2259. } else {
  2260. scr = existing;
  2261. }
  2262. break;
  2263. case ResourceFormatLoader::CACHE_MODE_REPLACE:
  2264. case ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP:
  2265. scr->set_path(p_original_path, true);
  2266. break;
  2267. }
  2268. scr->reload();
  2269. if (r_error) {
  2270. *r_error = OK;
  2271. }
  2272. return scr;
  2273. }
  2274. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2275. p_extensions->push_back("cs");
  2276. }
  2277. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2278. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2279. }
  2280. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2281. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2282. }
  2283. Error ResourceFormatSaverCSharpScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  2284. Ref<CSharpScript> sqscr = p_resource;
  2285. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2286. String source = sqscr->get_source_code();
  2287. #ifdef TOOLS_ENABLED
  2288. if (!FileAccess::exists(p_path)) {
  2289. // The file does not yet exist, let's assume the user just created this script. In such
  2290. // cases we need to check whether the solution and csproj were already created or not.
  2291. if (!_create_project_solution_if_needed()) {
  2292. ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
  2293. }
  2294. }
  2295. #endif
  2296. {
  2297. Error err;
  2298. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2299. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2300. file->store_string(source);
  2301. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2302. return ERR_CANT_CREATE;
  2303. }
  2304. }
  2305. #ifdef TOOLS_ENABLED
  2306. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2307. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2308. }
  2309. #endif
  2310. return OK;
  2311. }
  2312. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  2313. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2314. p_extensions->push_back("cs");
  2315. }
  2316. }
  2317. bool ResourceFormatSaverCSharpScript::recognize(const Ref<Resource> &p_resource) const {
  2318. return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
  2319. }