csharp_script.cpp 82 KB

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