csharp_script.cpp 88 KB

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