csharp_script.cpp 87 KB

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