csharp_script.cpp 89 KB

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