csharp_script.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 <mono/metadata/threads.h>
  32. #include "core/io/json.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "core/os/thread.h"
  36. #include "core/project_settings.h"
  37. #ifdef TOOLS_ENABLED
  38. #include "editor/bindings_generator.h"
  39. #include "editor/csharp_project.h"
  40. #include "editor/editor_node.h"
  41. #include "editor/godotsharp_editor.h"
  42. #endif
  43. #include "godotsharp_dirs.h"
  44. #include "mono_gd/gd_mono_class.h"
  45. #include "mono_gd/gd_mono_marshal.h"
  46. #include "signal_awaiter_utils.h"
  47. #include "utils/macros.h"
  48. #include "utils/mutex_utils.h"
  49. #include "utils/string_utils.h"
  50. #include "utils/thread_local.h"
  51. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  52. #ifdef TOOLS_ENABLED
  53. static bool _create_project_solution_if_needed() {
  54. String sln_path = GodotSharpDirs::get_project_sln_path();
  55. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  56. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  57. // A solution does not yet exist, create a new one
  58. CRASH_COND(GodotSharpEditor::get_singleton() == NULL);
  59. return GodotSharpEditor::get_singleton()->call("_create_project_solution");
  60. }
  61. return true;
  62. }
  63. #endif
  64. CSharpLanguage *CSharpLanguage::singleton = NULL;
  65. String CSharpLanguage::get_name() const {
  66. return "C#";
  67. }
  68. String CSharpLanguage::get_type() const {
  69. return "CSharpScript";
  70. }
  71. String CSharpLanguage::get_extension() const {
  72. return "cs";
  73. }
  74. Error CSharpLanguage::execute_file(const String &p_path) {
  75. // ??
  76. return OK;
  77. }
  78. #ifdef TOOLS_ENABLED
  79. void gdsharp_editor_init_callback() {
  80. EditorNode *editor = EditorNode::get_singleton();
  81. editor->add_child(memnew(GodotSharpEditor(editor)));
  82. }
  83. #endif
  84. void CSharpLanguage::init() {
  85. gdmono = memnew(GDMono);
  86. gdmono->initialize();
  87. #ifndef MONO_GLUE_ENABLED
  88. WARN_PRINT("This binary is built with `mono_glue=no` and cannot be used for scripting");
  89. #endif
  90. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  91. if (gdmono->get_editor_tools_assembly() != NULL) {
  92. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  93. BindingsGenerator::handle_cmdline_args(cmdline_args);
  94. }
  95. #endif
  96. #ifdef TOOLS_ENABLED
  97. EditorNode::add_init_callback(&gdsharp_editor_init_callback);
  98. GLOBAL_DEF("mono/export/include_scripts_content", false);
  99. #endif
  100. }
  101. void CSharpLanguage::finish() {
  102. finalizing = true;
  103. #ifdef TOOLS_ENABLED
  104. // Must be here, to avoid StringName leaks
  105. if (BindingsGenerator::singleton) {
  106. memdelete(BindingsGenerator::singleton);
  107. BindingsGenerator::singleton = NULL;
  108. }
  109. #endif
  110. // Make sure all script binding gchandles are released before finalizing GDMono
  111. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  112. CSharpScriptBinding &script_binding = E->value();
  113. if (script_binding.gchandle.is_valid()) {
  114. script_binding.gchandle->release();
  115. script_binding.inited = false;
  116. }
  117. }
  118. if (gdmono) {
  119. memdelete(gdmono);
  120. gdmono = NULL;
  121. }
  122. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  123. script_bindings.clear();
  124. finalizing = false;
  125. }
  126. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  127. static const char *_reserved_words[] = {
  128. // Reserved keywords
  129. "abstract",
  130. "as",
  131. "base",
  132. "bool",
  133. "break",
  134. "byte",
  135. "case",
  136. "catch",
  137. "char",
  138. "checked",
  139. "class",
  140. "const",
  141. "continue",
  142. "decimal",
  143. "default",
  144. "delegate",
  145. "do",
  146. "double",
  147. "else",
  148. "enum",
  149. "event",
  150. "explicit",
  151. "extern",
  152. "false",
  153. "finally",
  154. "fixed",
  155. "float",
  156. "for",
  157. "foreach",
  158. "goto",
  159. "if",
  160. "implicit",
  161. "in",
  162. "int",
  163. "interface",
  164. "internal",
  165. "is",
  166. "lock",
  167. "long",
  168. "namespace",
  169. "new",
  170. "null",
  171. "object",
  172. "operator",
  173. "out",
  174. "override",
  175. "params",
  176. "private",
  177. "protected",
  178. "public",
  179. "readonly",
  180. "ref",
  181. "return",
  182. "sbyte",
  183. "sealed",
  184. "short",
  185. "sizeof",
  186. "stackalloc",
  187. "static",
  188. "string",
  189. "struct",
  190. "switch",
  191. "this",
  192. "throw",
  193. "true",
  194. "try",
  195. "typeof",
  196. "uint",
  197. "ulong",
  198. "unchecked",
  199. "unsafe",
  200. "ushort",
  201. "using",
  202. "virtual",
  203. "void",
  204. "volatile",
  205. "while",
  206. // Contextual keywords. Not reserved words, but I guess we should include
  207. // them because this seems to be used only for syntax highlighting.
  208. "add",
  209. "alias",
  210. "ascending",
  211. "async",
  212. "await",
  213. "by",
  214. "descending",
  215. "dynamic",
  216. "equals",
  217. "from",
  218. "get",
  219. "global",
  220. "group",
  221. "into",
  222. "join",
  223. "let",
  224. "nameof",
  225. "on",
  226. "orderby",
  227. "partial",
  228. "remove",
  229. "select",
  230. "set",
  231. "value",
  232. "var",
  233. "when",
  234. "where",
  235. "yield",
  236. 0
  237. };
  238. const char **w = _reserved_words;
  239. while (*w) {
  240. p_words->push_back(*w);
  241. w++;
  242. }
  243. }
  244. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  245. p_delimiters->push_back("//"); // single-line comment
  246. p_delimiters->push_back("/* */"); // delimited comment
  247. }
  248. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  249. p_delimiters->push_back("' '"); // character literal
  250. p_delimiters->push_back("\" \""); // regular string literal
  251. p_delimiters->push_back("@\" \""); // verbatim string literal
  252. }
  253. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  254. String base_class = p_base_class_name;
  255. if (p_class_name == base_class) {
  256. base_class = "Godot." + base_class;
  257. }
  258. return base_class;
  259. }
  260. Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  261. String script_template = "using " BINDINGS_NAMESPACE ";\n"
  262. "using System;\n"
  263. "\n"
  264. "public class %CLASS% : %BASE%\n"
  265. "{\n"
  266. " // Declare member variables here. Examples:\n"
  267. " // private int a = 2;\n"
  268. " // private string b = \"text\";\n"
  269. "\n"
  270. " // Called when the node enters the scene tree for the first time.\n"
  271. " public override void _Ready()\n"
  272. " {\n"
  273. " \n"
  274. " }\n"
  275. "\n"
  276. "// // Called every frame. 'delta' is the elapsed time since the previous frame.\n"
  277. "// public override void _Process(float delta)\n"
  278. "// {\n"
  279. "// \n"
  280. "// }\n"
  281. "}\n";
  282. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  283. script_template = script_template.replace("%BASE%", base_class_name)
  284. .replace("%CLASS%", p_class_name);
  285. Ref<CSharpScript> script;
  286. script.instance();
  287. script->set_source_code(script_template);
  288. script->set_name(p_class_name);
  289. return script;
  290. }
  291. bool CSharpLanguage::is_using_templates() {
  292. return true;
  293. }
  294. void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  295. String src = p_script->get_source_code();
  296. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  297. src = src.replace("%BASE%", base_class_name)
  298. .replace("%CLASS%", p_class_name)
  299. .replace("%TS%", _get_indentation());
  300. p_script->set_source_code(src);
  301. }
  302. String CSharpLanguage::validate_path(const String &p_path) const {
  303. String class_name = p_path.get_file().get_basename();
  304. List<String> keywords;
  305. get_reserved_words(&keywords);
  306. if (keywords.find(class_name)) {
  307. return TTR("Class name can't be a reserved keyword");
  308. }
  309. return "";
  310. }
  311. Script *CSharpLanguage::create_script() const {
  312. return memnew(CSharpScript);
  313. }
  314. bool CSharpLanguage::has_named_classes() const {
  315. return false;
  316. }
  317. bool CSharpLanguage::supports_builtin_mode() const {
  318. return false;
  319. }
  320. #ifdef TOOLS_ENABLED
  321. static String variant_type_to_managed_name(const String &p_var_type_name) {
  322. if (p_var_type_name.empty())
  323. return "object";
  324. if (!ClassDB::class_exists(p_var_type_name)) {
  325. return p_var_type_name;
  326. }
  327. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
  328. return "Godot.Object";
  329. if (p_var_type_name == Variant::get_type_name(Variant::REAL)) {
  330. #ifdef REAL_T_IS_DOUBLE
  331. return "double";
  332. #else
  333. return "float";
  334. #endif
  335. }
  336. if (p_var_type_name == Variant::get_type_name(Variant::STRING))
  337. return "string"; // I prefer this one >:[
  338. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
  339. return "Collections.Dictionary";
  340. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
  341. return "Collections.Array";
  342. if (p_var_type_name == Variant::get_type_name(Variant::POOL_BYTE_ARRAY))
  343. return "byte[]";
  344. if (p_var_type_name == Variant::get_type_name(Variant::POOL_INT_ARRAY))
  345. return "int[]";
  346. if (p_var_type_name == Variant::get_type_name(Variant::POOL_REAL_ARRAY)) {
  347. #ifdef REAL_T_IS_DOUBLE
  348. return "double[]";
  349. #else
  350. return "float[]";
  351. #endif
  352. }
  353. if (p_var_type_name == Variant::get_type_name(Variant::POOL_STRING_ARRAY))
  354. return "string[]";
  355. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR2_ARRAY))
  356. return "Vector2[]";
  357. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR3_ARRAY))
  358. return "Vector3[]";
  359. if (p_var_type_name == Variant::get_type_name(Variant::POOL_COLOR_ARRAY))
  360. return "Color[]";
  361. Variant::Type var_types[] = {
  362. Variant::BOOL,
  363. Variant::INT,
  364. Variant::VECTOR2,
  365. Variant::RECT2,
  366. Variant::VECTOR3,
  367. Variant::TRANSFORM2D,
  368. Variant::PLANE,
  369. Variant::QUAT,
  370. Variant::AABB,
  371. Variant::BASIS,
  372. Variant::TRANSFORM,
  373. Variant::COLOR,
  374. Variant::NODE_PATH,
  375. Variant::_RID
  376. };
  377. for (int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  378. if (p_var_type_name == Variant::get_type_name(var_types[i]))
  379. return p_var_type_name;
  380. }
  381. return "object";
  382. }
  383. String CSharpLanguage::make_function(const String &, const String &p_name, const PoolStringArray &p_args) const {
  384. // FIXME
  385. // - Due to Godot's API limitation this just appends the function to the end of the file
  386. // - Use fully qualified name if there is ambiguity
  387. String s = "private void " + p_name + "(";
  388. for (int i = 0; i < p_args.size(); i++) {
  389. const String &arg = p_args[i];
  390. if (i > 0)
  391. s += ", ";
  392. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  393. }
  394. s += ")\n{\n // Replace with function body.\n}\n";
  395. return s;
  396. }
  397. #else
  398. String CSharpLanguage::make_function(const String &, const String &, const PoolStringArray &) const {
  399. return String();
  400. }
  401. #endif
  402. String CSharpLanguage::_get_indentation() const {
  403. #ifdef TOOLS_ENABLED
  404. if (Engine::get_singleton()->is_editor_hint()) {
  405. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);
  406. if (use_space_indentation) {
  407. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  408. String space_indent = "";
  409. for (int i = 0; i < indent_size; i++) {
  410. space_indent += " ";
  411. }
  412. return space_indent;
  413. }
  414. }
  415. #endif
  416. return "\t";
  417. }
  418. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  419. #ifdef DEBUG_ENABLED
  420. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  421. if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoUtils::mono_cache.corlib_cache_updated)
  422. return Vector<StackInfo>();
  423. MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
  424. MonoBoolean need_file_info = true;
  425. void *ctor_args[1] = { &need_file_info };
  426. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
  427. Vector<StackInfo> si;
  428. si = stack_trace_get_info(stack_trace);
  429. return si;
  430. #else
  431. return Vector<StackInfo>();
  432. #endif
  433. }
  434. #ifdef DEBUG_ENABLED
  435. Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
  436. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  437. MonoException *exc = NULL;
  438. MonoArray *frames = invoke_method_thunk(CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames), p_stack_trace, (MonoObject **)&exc);
  439. if (exc) {
  440. GDMonoUtils::debug_print_unhandled_exception(exc);
  441. return Vector<StackInfo>();
  442. }
  443. int frame_count = mono_array_length(frames);
  444. if (frame_count <= 0)
  445. return Vector<StackInfo>();
  446. GDMonoUtils::DebugUtils_StackFrameInfo get_sf_info = CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo);
  447. Vector<StackInfo> si;
  448. si.resize(frame_count);
  449. for (int i = 0; i < frame_count; i++) {
  450. StackInfo &sif = si.write[i];
  451. MonoObject *frame = mono_array_get(frames, MonoObject *, i);
  452. MonoString *file_name;
  453. int file_line_num;
  454. MonoString *method_decl;
  455. invoke_method_thunk(get_sf_info, frame, &file_name, &file_line_num, &method_decl, (MonoObject **)&exc);
  456. if (exc) {
  457. GDMonoUtils::debug_print_unhandled_exception(exc);
  458. return Vector<StackInfo>();
  459. }
  460. // TODO
  461. // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
  462. // can reproduce with a MissingMethodException on internal calls
  463. sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
  464. sif.line = file_line_num;
  465. sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
  466. }
  467. return si;
  468. }
  469. #endif
  470. void CSharpLanguage::frame() {
  471. if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) {
  472. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle;
  473. if (task_scheduler_handle.is_valid()) {
  474. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  475. if (task_scheduler) {
  476. MonoException *exc = NULL;
  477. invoke_method_thunk(CACHED_METHOD_THUNK(GodotTaskScheduler, Activate), task_scheduler, (MonoObject **)&exc);
  478. if (exc) {
  479. GDMonoUtils::debug_unhandled_exception(exc);
  480. GD_UNREACHABLE();
  481. }
  482. }
  483. }
  484. }
  485. }
  486. struct CSharpScriptDepSort {
  487. // must support sorting so inheritance works properly (parent must be reloaded first)
  488. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  489. if (A == B)
  490. return false; // shouldn't happen but..
  491. GDMonoClass *I = B->base;
  492. while (I) {
  493. if (I == A->script_class) {
  494. // A is a base of B
  495. return true;
  496. }
  497. I = I->get_parent_class();
  498. }
  499. return false; // not a base
  500. }
  501. };
  502. void CSharpLanguage::reload_all_scripts() {
  503. #ifdef GD_MONO_HOT_RELOAD
  504. if (is_assembly_reloading_needed()) {
  505. reload_assemblies(false);
  506. }
  507. #endif
  508. }
  509. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  510. (void)p_script; // UNUSED
  511. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  512. #ifdef TOOLS_ENABLED
  513. MonoReloadNode::get_singleton()->restart_reload_timer();
  514. #endif
  515. #ifdef GD_MONO_HOT_RELOAD
  516. if (is_assembly_reloading_needed()) {
  517. reload_assemblies(p_soft_reload);
  518. }
  519. #endif
  520. }
  521. #ifdef GD_MONO_HOT_RELOAD
  522. bool CSharpLanguage::is_assembly_reloading_needed() {
  523. if (!gdmono->is_runtime_initialized())
  524. return false;
  525. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  526. String name = ProjectSettings::get_singleton()->get("application/config/name");
  527. if (name.empty()) {
  528. name = "UnnamedProject";
  529. }
  530. name += ".dll";
  531. if (proj_assembly) {
  532. String proj_asm_path = proj_assembly->get_path();
  533. if (!FileAccess::exists(proj_assembly->get_path())) {
  534. // Maybe it wasn't loaded from the default path, so check this as well
  535. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name);
  536. if (!FileAccess::exists(proj_asm_path))
  537. return false; // No assembly to load
  538. }
  539. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  540. return false; // Already up to date
  541. } else {
  542. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name)))
  543. return false; // No assembly to load
  544. }
  545. #ifdef TOOLS_ENABLED
  546. if (!gdmono->get_core_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE))
  547. return false; // The core API assembly to load is invalidated
  548. if (!gdmono->get_editor_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR))
  549. return false; // The editor API assembly to load is invalidated
  550. #endif
  551. return true;
  552. }
  553. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  554. if (!gdmono->is_runtime_initialized())
  555. return;
  556. // There is no soft reloading with Mono. It's always hard reloading.
  557. List<Ref<CSharpScript> > scripts;
  558. {
  559. SCOPED_MUTEX_LOCK(script_instances_mutex);
  560. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  561. if (elem->self()->get_path().is_resource_file()) {
  562. // Cast to CSharpScript to avoid being erased by accident
  563. scripts.push_back(Ref<CSharpScript>(elem->self()));
  564. }
  565. }
  566. }
  567. List<Ref<CSharpScript> > to_reload;
  568. // As scripts are going to be reloaded, must proceed without locking here
  569. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  570. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  571. Ref<CSharpScript> &script = E->get();
  572. to_reload.push_back(script);
  573. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  574. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  575. for (Set<Object *>::Element *E = script->instances.front(); E; E = E->next()) {
  576. script->pending_reload_instances.insert(E->get()->get_instance_id());
  577. }
  578. #ifdef TOOLS_ENABLED
  579. for (Set<PlaceHolderScriptInstance *>::Element *E = script->placeholders.front(); E; E = E->next()) {
  580. script->pending_reload_instances.insert(E->get()->get_owner()->get_instance_id());
  581. }
  582. #endif
  583. // FIXME: What about references? Need to keep them alive if only managed code references them.
  584. // Save state and remove script from instances
  585. Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
  586. while (script->instances.front()) {
  587. Object *obj = script->instances.front()->get();
  588. // Save instance info
  589. CSharpScript::StateBackup state;
  590. ERR_CONTINUE(!obj->get_script_instance());
  591. // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
  592. obj->get_script_instance()->get_property_state(state.properties);
  593. Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle;
  594. if (gchandle.is_valid())
  595. gchandle->release();
  596. owners_map[obj->get_instance_id()] = state;
  597. obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  598. }
  599. script->_clear();
  600. }
  601. // Do domain reload
  602. if (gdmono->reload_scripts_domain() != OK) {
  603. // Failed to reload the scripts domain
  604. // Make sure to add the scripts back to their owners before returning
  605. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  606. Ref<CSharpScript> scr = E->get();
  607. for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
  608. Object *obj = ObjectDB::get_instance(F->key());
  609. if (!obj)
  610. continue;
  611. ObjectID obj_id = obj->get_instance_id();
  612. // Use a placeholder for now to avoid losing the state when saving a scene
  613. obj->set_script(scr.get_ref_ptr());
  614. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  615. obj->set_script_instance(placeholder);
  616. #ifdef TOOLS_ENABLED
  617. // Even though build didn't fail, this tells the placeholder to keep properties and
  618. // it allows using property_set_fallback for restoring the state without a valid script.
  619. scr->placeholder_fallback_enabled = true;
  620. #endif
  621. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  622. for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
  623. placeholder->property_set_fallback(G->get().first, G->get().second, NULL);
  624. }
  625. scr->pending_reload_state.erase(obj_id);
  626. }
  627. }
  628. return;
  629. }
  630. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  631. Ref<CSharpScript> scr = E->get();
  632. #ifdef TOOLS_ENABLED
  633. scr->exports_invalidated = true;
  634. #endif
  635. scr->signals_invalidated = true;
  636. scr->reload(p_soft_reload);
  637. scr->update_exports();
  638. {
  639. for (Set<ObjectID>::Element *F = scr->pending_reload_instances.front(); F; F = F->next()) {
  640. ObjectID obj_id = F->get();
  641. Object *obj = ObjectDB::get_instance(obj_id);
  642. if (!obj) {
  643. scr->pending_reload_state.erase(obj_id);
  644. continue;
  645. }
  646. ScriptInstance *si = obj->get_script_instance();
  647. #ifdef TOOLS_ENABLED
  648. if (si) {
  649. // If the script instance is not null, then it must be a placeholder.
  650. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  651. CRASH_COND(!si->is_placeholder());
  652. if (scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  653. // Replace placeholder with a script instance
  654. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  655. // Backup placeholder script instance state before replacing it with a script instance
  656. si->get_property_state(state_backup.properties);
  657. ScriptInstance *script_instance = scr->instance_create(obj);
  658. if (script_instance) {
  659. scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  660. obj->set_script_instance(script_instance);
  661. }
  662. // TODO: Restore serialized state
  663. for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
  664. script_instance->set(G->get().first, G->get().second);
  665. }
  666. scr->pending_reload_state.erase(obj_id);
  667. }
  668. continue;
  669. }
  670. #else
  671. CRASH_COND(si != NULL);
  672. #endif
  673. // Re-create script instance
  674. obj->set_script(scr.get_ref_ptr()); // will create the script instance as well
  675. // TODO: Restore serialized state
  676. for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
  677. obj->get_script_instance()->set(G->get().first, G->get().second);
  678. }
  679. scr->pending_reload_state.erase(obj_id);
  680. }
  681. scr->pending_reload_instances.clear();
  682. }
  683. }
  684. #ifdef TOOLS_ENABLED
  685. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  686. if (Engine::get_singleton()->is_editor_hint()) {
  687. EditorNode::get_singleton()->get_inspector()->update_tree();
  688. NodeDock::singleton->update_lists();
  689. }
  690. #endif
  691. }
  692. #endif
  693. void CSharpLanguage::project_assembly_loaded() {
  694. scripts_metadata.clear();
  695. String scripts_metadata_filename = "scripts_metadata.";
  696. #ifdef TOOLS_ENABLED
  697. scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player";
  698. #else
  699. #ifdef DEBUG_ENABLED
  700. scripts_metadata_filename += "debug";
  701. #else
  702. scripts_metadata_filename += "release";
  703. #endif
  704. #endif
  705. String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename);
  706. if (FileAccess::exists(scripts_metadata_path)) {
  707. String old_json;
  708. Error ferr = read_all_file_utf8(scripts_metadata_path, old_json);
  709. ERR_FAIL_COND(ferr != OK);
  710. Variant old_dict_var;
  711. String err_str;
  712. int err_line;
  713. Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line);
  714. if (json_err != OK) {
  715. ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ")");
  716. return;
  717. }
  718. scripts_metadata = old_dict_var.operator Dictionary();
  719. print_verbose("Successfully loaded scripts metadata");
  720. } else {
  721. if (!Engine::get_singleton()->is_editor_hint()) {
  722. ERR_PRINT("Missing scripts metadata file");
  723. }
  724. }
  725. }
  726. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  727. p_extensions->push_back("cs");
  728. }
  729. #ifdef TOOLS_ENABLED
  730. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  731. return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col);
  732. }
  733. bool CSharpLanguage::overrides_external_editor() {
  734. return GodotSharpEditor::get_singleton()->overrides_external_editor();
  735. }
  736. #endif
  737. void CSharpLanguage::thread_enter() {
  738. #if 0
  739. if (mono->is_runtime_initialized()) {
  740. GDMonoUtils::attach_current_thread();
  741. }
  742. #endif
  743. }
  744. void CSharpLanguage::thread_exit() {
  745. #if 0
  746. if (mono->is_runtime_initialized()) {
  747. GDMonoUtils::detach_current_thread();
  748. }
  749. #endif
  750. }
  751. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  752. // Break because of parse error
  753. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  754. // TODO
  755. //_debug_parse_err_line = p_line;
  756. //_debug_parse_err_file = p_file;
  757. //_debug_error = p_error;
  758. ScriptDebugger::get_singleton()->debug(this, false);
  759. return true;
  760. } else {
  761. return false;
  762. }
  763. }
  764. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  765. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  766. // TODO
  767. //_debug_parse_err_line = -1;
  768. //_debug_parse_err_file = "";
  769. //_debug_error = p_error;
  770. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  771. return true;
  772. } else {
  773. return false;
  774. }
  775. }
  776. void CSharpLanguage::set_language_index(int p_idx) {
  777. ERR_FAIL_COND(lang_idx != -1);
  778. lang_idx = p_idx;
  779. }
  780. void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) {
  781. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  782. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  783. p_gchandle->release();
  784. }
  785. }
  786. void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle) {
  787. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_expected_obj); // We might lock after this, so pin it
  788. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  789. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  790. MonoObject *target = p_gchandle->get_target();
  791. // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
  792. // already released and could have been replaced) or if we can't get its target MonoObject*
  793. // (which doesn't necessarily mean it was released, and we want it released in order to
  794. // avoid locking other threads unnecessarily).
  795. if (target == p_expected_obj || target == NULL) {
  796. p_gchandle->release();
  797. }
  798. }
  799. MonoGCHandle::free_handle(pinned_gchandle);
  800. }
  801. CSharpLanguage::CSharpLanguage() {
  802. ERR_FAIL_COND(singleton);
  803. singleton = this;
  804. finalizing = false;
  805. gdmono = NULL;
  806. #ifdef NO_THREADS
  807. script_instances_mutex = NULL;
  808. script_gchandle_release_mutex = NULL;
  809. language_bind_mutex = NULL;
  810. #else
  811. script_instances_mutex = Mutex::create();
  812. script_gchandle_release_mutex = Mutex::create();
  813. language_bind_mutex = Mutex::create();
  814. #endif
  815. lang_idx = -1;
  816. }
  817. CSharpLanguage::~CSharpLanguage() {
  818. finish();
  819. if (script_instances_mutex) {
  820. memdelete(script_instances_mutex);
  821. script_instances_mutex = NULL;
  822. }
  823. if (language_bind_mutex) {
  824. memdelete(language_bind_mutex);
  825. language_bind_mutex = NULL;
  826. }
  827. if (script_gchandle_release_mutex) {
  828. memdelete(script_gchandle_release_mutex);
  829. script_gchandle_release_mutex = NULL;
  830. }
  831. singleton = NULL;
  832. }
  833. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  834. #ifdef DEBUG_ENABLED
  835. // I don't trust you
  836. if (p_object->get_script_instance()) {
  837. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  838. CRASH_COND(csharp_instance != NULL && !csharp_instance->is_destructing_script_instance());
  839. }
  840. #endif
  841. StringName type_name = p_object->get_class_name();
  842. // ¯\_(ツ)_/¯
  843. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  844. while (classinfo && !classinfo->exposed)
  845. classinfo = classinfo->inherits_ptr;
  846. ERR_FAIL_NULL_V(classinfo, false);
  847. type_name = classinfo->name;
  848. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  849. ERR_FAIL_NULL_V(type_class, false);
  850. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  851. ERR_FAIL_NULL_V(mono_object, false);
  852. r_script_binding.inited = true;
  853. r_script_binding.type_name = type_name;
  854. r_script_binding.wrapper_class = type_class; // cache
  855. r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
  856. // Tie managed to unmanaged
  857. Reference *ref = Object::cast_to<Reference>(p_object);
  858. if (ref) {
  859. // Unsafe refcount increment. The managed instance also counts as a reference.
  860. // This way if the unmanaged world has no references to our owner
  861. // but the managed instance is alive, the refcount will be 1 instead of 0.
  862. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  863. ref->reference();
  864. }
  865. return true;
  866. }
  867. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  868. SCOPED_MUTEX_LOCK(language_bind_mutex);
  869. Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
  870. if (match)
  871. return (void *)match;
  872. CSharpScriptBinding script_binding;
  873. if (!setup_csharp_script_binding(script_binding, p_object))
  874. return NULL;
  875. return (void *)insert_script_binding(p_object, script_binding);
  876. }
  877. Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  878. return script_bindings.insert(p_object, p_script_binding);
  879. }
  880. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  881. if (GDMono::get_singleton() == NULL) {
  882. #ifdef DEBUG_ENABLED
  883. CRASH_COND(!script_bindings.empty());
  884. #endif
  885. // Mono runtime finalized, all the gchandle bindings were already released
  886. return;
  887. }
  888. if (finalizing)
  889. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  890. {
  891. SCOPED_MUTEX_LOCK(language_bind_mutex);
  892. Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;
  893. CSharpScriptBinding &script_binding = data->value();
  894. if (script_binding.inited) {
  895. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  896. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  897. MonoObject *mono_object = script_binding.gchandle->get_target();
  898. if (mono_object) {
  899. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  900. }
  901. }
  902. script_bindings.erase(data);
  903. }
  904. }
  905. void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
  906. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  907. #ifdef DEBUG_ENABLED
  908. CRASH_COND(!ref_owner);
  909. #endif
  910. void *data = p_object->get_script_instance_binding(get_language_index());
  911. CRASH_COND(!data);
  912. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  913. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  914. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  915. // The reference count was increased after the managed side was the only one referencing our owner.
  916. // This means the owner is being referenced again by the unmanaged side,
  917. // so the owner must hold the managed side alive again to avoid it from being GCed.
  918. MonoObject *target = gchandle->get_target();
  919. if (!target)
  920. return; // Called after the managed side was collected, so nothing to do here
  921. // Release the current weak handle and replace it with a strong handle.
  922. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target);
  923. gchandle->release();
  924. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  925. }
  926. }
  927. bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
  928. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  929. #ifdef DEBUG_ENABLED
  930. CRASH_COND(!ref_owner);
  931. #endif
  932. int refcount = ref_owner->reference_get_count();
  933. void *data = p_object->get_script_instance_binding(get_language_index());
  934. CRASH_COND(!data);
  935. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  936. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  937. if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  938. // If owner owner is no longer referenced by the unmanaged side,
  939. // the managed instance takes responsibility of deleting the owner when GCed.
  940. MonoObject *target = gchandle->get_target();
  941. if (!target)
  942. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  943. // Release the current strong handle and replace it with a weak handle.
  944. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target);
  945. gchandle->release();
  946. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  947. return false;
  948. }
  949. return refcount == 0;
  950. }
  951. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  952. CSharpInstance *instance = memnew(CSharpInstance);
  953. Reference *ref = Object::cast_to<Reference>(p_owner);
  954. instance->base_ref = ref != NULL;
  955. instance->script = Ref<CSharpScript>(p_script);
  956. instance->owner = p_owner;
  957. instance->gchandle = p_gchandle;
  958. if (instance->base_ref)
  959. instance->_reference_owner_unsafe();
  960. p_script->instances.insert(p_owner);
  961. return instance;
  962. }
  963. MonoObject *CSharpInstance::get_mono_object() const {
  964. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  965. return gchandle->get_target();
  966. }
  967. Object *CSharpInstance::get_owner() {
  968. return owner;
  969. }
  970. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  971. ERR_FAIL_COND_V(!script.is_valid(), false);
  972. MonoObject *mono_object = get_mono_object();
  973. ERR_FAIL_NULL_V(mono_object, false);
  974. GDMonoClass *top = script->script_class;
  975. while (top && top != script->native) {
  976. GDMonoField *field = script->script_class->get_field(p_name);
  977. if (field) {
  978. field->set_value_from_variant(mono_object, p_value);
  979. return true;
  980. }
  981. GDMonoProperty *property = script->script_class->get_property(p_name);
  982. if (property) {
  983. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
  984. return true;
  985. }
  986. top = top->get_parent_class();
  987. }
  988. // Call _set
  989. top = script->script_class;
  990. while (top && top != script->native) {
  991. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  992. if (method) {
  993. Variant name = p_name;
  994. const Variant *args[2] = { &name, &p_value };
  995. MonoObject *ret = method->invoke(mono_object, args);
  996. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
  997. return true;
  998. break;
  999. }
  1000. top = top->get_parent_class();
  1001. }
  1002. return false;
  1003. }
  1004. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1005. ERR_FAIL_COND_V(!script.is_valid(), false);
  1006. MonoObject *mono_object = get_mono_object();
  1007. ERR_FAIL_NULL_V(mono_object, false);
  1008. GDMonoClass *top = script->script_class;
  1009. while (top && top != script->native) {
  1010. GDMonoField *field = top->get_field(p_name);
  1011. if (field) {
  1012. MonoObject *value = field->get_value(mono_object);
  1013. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1014. return true;
  1015. }
  1016. GDMonoProperty *property = top->get_property(p_name);
  1017. if (property) {
  1018. MonoException *exc = NULL;
  1019. MonoObject *value = property->get_value(mono_object, &exc);
  1020. if (exc) {
  1021. r_ret = Variant();
  1022. GDMonoUtils::set_pending_exception(exc);
  1023. } else {
  1024. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1025. }
  1026. return true;
  1027. }
  1028. top = top->get_parent_class();
  1029. }
  1030. // Call _get
  1031. top = script->script_class;
  1032. while (top && top != script->native) {
  1033. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  1034. if (method) {
  1035. Variant name = p_name;
  1036. const Variant *args[1] = { &name };
  1037. MonoObject *ret = method->invoke(mono_object, args);
  1038. if (ret) {
  1039. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  1040. return true;
  1041. }
  1042. break;
  1043. }
  1044. top = top->get_parent_class();
  1045. }
  1046. return false;
  1047. }
  1048. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1049. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  1050. p_properties->push_back(E->value());
  1051. }
  1052. }
  1053. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1054. if (script->member_info.has(p_name)) {
  1055. if (r_is_valid)
  1056. *r_is_valid = true;
  1057. return script->member_info[p_name].type;
  1058. }
  1059. if (r_is_valid)
  1060. *r_is_valid = false;
  1061. return Variant::NIL;
  1062. }
  1063. bool CSharpInstance::has_method(const StringName &p_method) const {
  1064. if (!script.is_valid())
  1065. return false;
  1066. GDMonoClass *top = script->script_class;
  1067. while (top && top != script->native) {
  1068. if (top->has_fetched_method_unknown_params(p_method)) {
  1069. return true;
  1070. }
  1071. top = top->get_parent_class();
  1072. }
  1073. return false;
  1074. }
  1075. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1076. MonoObject *mono_object = get_mono_object();
  1077. if (!mono_object) {
  1078. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1079. ERR_FAIL_V(Variant());
  1080. }
  1081. if (!script.is_valid())
  1082. ERR_FAIL_V(Variant());
  1083. GDMonoClass *top = script->script_class;
  1084. while (top && top != script->native) {
  1085. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1086. if (method) {
  1087. MonoObject *return_value = method->invoke(mono_object, p_args);
  1088. r_error.error = Variant::CallError::CALL_OK;
  1089. if (return_value) {
  1090. return GDMonoMarshal::mono_object_to_variant(return_value);
  1091. } else {
  1092. return Variant();
  1093. }
  1094. }
  1095. top = top->get_parent_class();
  1096. }
  1097. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1098. return Variant();
  1099. }
  1100. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1101. if (script.is_valid()) {
  1102. MonoObject *mono_object = get_mono_object();
  1103. ERR_FAIL_NULL(mono_object);
  1104. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  1105. }
  1106. }
  1107. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  1108. GDMonoClass *top = script->script_class;
  1109. while (top && top != script->native) {
  1110. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1111. if (method) {
  1112. method->invoke(p_mono_object, p_args);
  1113. return;
  1114. }
  1115. top = top->get_parent_class();
  1116. }
  1117. }
  1118. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1119. // Sorry, the method is the one that controls the call order
  1120. call_multilevel(p_method, p_args, p_argcount);
  1121. }
  1122. bool CSharpInstance::_reference_owner_unsafe() {
  1123. #ifdef DEBUG_ENABLED
  1124. CRASH_COND(!base_ref);
  1125. CRASH_COND(owner == NULL);
  1126. CRASH_COND(unsafe_referenced); // already referenced
  1127. #endif
  1128. // Unsafe refcount increment. The managed instance also counts as a reference.
  1129. // This way if the unmanaged world has no references to our owner
  1130. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1131. // See: _unreference_owner_unsafe()
  1132. // May not me referenced yet, so we must use init_ref() instead of reference()
  1133. bool success = Object::cast_to<Reference>(owner)->init_ref();
  1134. unsafe_referenced = success;
  1135. return success;
  1136. }
  1137. bool CSharpInstance::_unreference_owner_unsafe() {
  1138. #ifdef DEBUG_ENABLED
  1139. CRASH_COND(!base_ref);
  1140. CRASH_COND(owner == NULL);
  1141. #endif
  1142. if (!unsafe_referenced)
  1143. return false; // Already unreferenced
  1144. unsafe_referenced = false;
  1145. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1146. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1147. // See: _reference_owner_unsafe()
  1148. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1149. return static_cast<Reference *>(owner)->unreference();
  1150. }
  1151. MonoObject *CSharpInstance::_internal_new_managed() {
  1152. #ifdef DEBUG_ENABLED
  1153. CRASH_COND(!gchandle.is_valid());
  1154. #endif
  1155. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1156. ERR_FAIL_NULL_V(owner, NULL);
  1157. ERR_FAIL_COND_V(script.is_null(), NULL);
  1158. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script->script_class->get_mono_ptr());
  1159. if (!mono_object) {
  1160. // Important to clear this before destroying the script instance here
  1161. script = Ref<CSharpScript>();
  1162. owner = NULL;
  1163. bool die = _unreference_owner_unsafe();
  1164. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  1165. CRASH_COND(die == true);
  1166. ERR_EXPLAIN("Failed to allocate memory for the object");
  1167. ERR_FAIL_V(NULL);
  1168. }
  1169. // Tie managed to unmanaged
  1170. gchandle = MonoGCHandle::create_strong(mono_object);
  1171. if (base_ref)
  1172. _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1173. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
  1174. // Construct
  1175. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1176. ctor->invoke_raw(mono_object, NULL);
  1177. return mono_object;
  1178. }
  1179. void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
  1180. #ifdef DEBUG_ENABLED
  1181. CRASH_COND(base_ref);
  1182. CRASH_COND(gchandle.is_null());
  1183. #endif
  1184. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1185. }
  1186. void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1187. #ifdef DEBUG_ENABLED
  1188. CRASH_COND(!base_ref);
  1189. CRASH_COND(gchandle.is_null());
  1190. #endif
  1191. r_remove_script_instance = false;
  1192. if (_unreference_owner_unsafe()) {
  1193. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1194. r_delete_owner = true;
  1195. } else {
  1196. r_delete_owner = false;
  1197. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1198. if (!p_is_finalizer) {
  1199. // If the native instance is still alive and Dispose() was called
  1200. // (instead of the finalizer), then we remove the script instance.
  1201. r_remove_script_instance = true;
  1202. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1203. // If the native instance is still alive and this is called from the finalizer,
  1204. // then it was referenced from another thread before the finalizer could
  1205. // unreference and delete it, so we want to keep it.
  1206. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1207. // could have already been collected. Instead we will create a new managed instance here.
  1208. MonoObject *new_managed = _internal_new_managed();
  1209. if (!new_managed) {
  1210. r_remove_script_instance = true;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. void CSharpInstance::refcount_incremented() {
  1216. #ifdef DEBUG_ENABLED
  1217. CRASH_COND(!base_ref);
  1218. CRASH_COND(owner == NULL);
  1219. #endif
  1220. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1221. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1222. // The reference count was increased after the managed side was the only one referencing our owner.
  1223. // This means the owner is being referenced again by the unmanaged side,
  1224. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1225. // Release the current weak handle and replace it with a strong handle.
  1226. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target());
  1227. gchandle->release();
  1228. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1229. }
  1230. }
  1231. bool CSharpInstance::refcount_decremented() {
  1232. #ifdef DEBUG_ENABLED
  1233. CRASH_COND(!base_ref);
  1234. CRASH_COND(owner == NULL);
  1235. #endif
  1236. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1237. int refcount = ref_owner->reference_get_count();
  1238. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1239. // If owner owner is no longer referenced by the unmanaged side,
  1240. // the managed instance takes responsibility of deleting the owner when GCed.
  1241. // Release the current strong handle and replace it with a weak handle.
  1242. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target());
  1243. gchandle->release();
  1244. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1245. return false;
  1246. }
  1247. ref_dying = (refcount == 0);
  1248. return ref_dying;
  1249. }
  1250. MultiplayerAPI::RPCMode CSharpInstance::_member_get_rpc_mode(IMonoClassMember *p_member) const {
  1251. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  1252. return MultiplayerAPI::RPC_MODE_REMOTE;
  1253. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  1254. return MultiplayerAPI::RPC_MODE_MASTER;
  1255. if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
  1256. return MultiplayerAPI::RPC_MODE_PUPPET;
  1257. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  1258. return MultiplayerAPI::RPC_MODE_PUPPET;
  1259. if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
  1260. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1261. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  1262. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1263. if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
  1264. return MultiplayerAPI::RPC_MODE_MASTERSYNC;
  1265. if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
  1266. return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
  1267. return MultiplayerAPI::RPC_MODE_DISABLED;
  1268. }
  1269. MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  1270. GDMonoClass *top = script->script_class;
  1271. while (top && top != script->native) {
  1272. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  1273. if (method && !method->is_static())
  1274. return _member_get_rpc_mode(method);
  1275. top = top->get_parent_class();
  1276. }
  1277. return MultiplayerAPI::RPC_MODE_DISABLED;
  1278. }
  1279. MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  1280. GDMonoClass *top = script->script_class;
  1281. while (top && top != script->native) {
  1282. GDMonoField *field = top->get_field(p_variable);
  1283. if (field && !field->is_static())
  1284. return _member_get_rpc_mode(field);
  1285. GDMonoProperty *property = top->get_property(p_variable);
  1286. if (property && !property->is_static())
  1287. return _member_get_rpc_mode(property);
  1288. top = top->get_parent_class();
  1289. }
  1290. return MultiplayerAPI::RPC_MODE_DISABLED;
  1291. }
  1292. void CSharpInstance::notification(int p_notification) {
  1293. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1294. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1295. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1296. // to be sent at least once, which happens right before the call to the destructor.
  1297. predelete_notified = true;
  1298. if (base_ref) {
  1299. // It's not safe to proceed if the owner derives Reference and the refcount reached 0.
  1300. // At this point, Dispose() was already called (manually or from the finalizer) so
  1301. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1302. // managed side references it and Dispose() needs to be called to release it.
  1303. // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
  1304. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1305. return;
  1306. }
  1307. _call_notification(p_notification);
  1308. MonoObject *mono_object = get_mono_object();
  1309. ERR_FAIL_NULL(mono_object);
  1310. MonoException *exc = NULL;
  1311. GDMonoUtils::dispose(mono_object, &exc);
  1312. if (exc) {
  1313. GDMonoUtils::set_pending_exception(exc);
  1314. }
  1315. return;
  1316. }
  1317. _call_notification(p_notification);
  1318. }
  1319. void CSharpInstance::_call_notification(int p_notification) {
  1320. MonoObject *mono_object = get_mono_object();
  1321. ERR_FAIL_NULL(mono_object);
  1322. // Custom version of _call_multilevel, optimized for _notification
  1323. uint32_t arg = p_notification;
  1324. void *args[1] = { &arg };
  1325. StringName method_name = CACHED_STRING_NAME(_notification);
  1326. GDMonoClass *top = script->script_class;
  1327. while (top && top != script->native) {
  1328. GDMonoMethod *method = top->get_method(method_name, 1);
  1329. if (method) {
  1330. method->invoke_raw(mono_object, args);
  1331. return;
  1332. }
  1333. top = top->get_parent_class();
  1334. }
  1335. }
  1336. Ref<Script> CSharpInstance::get_script() const {
  1337. return script;
  1338. }
  1339. ScriptLanguage *CSharpInstance::get_language() {
  1340. return CSharpLanguage::get_singleton();
  1341. }
  1342. CSharpInstance::CSharpInstance() :
  1343. owner(NULL),
  1344. base_ref(false),
  1345. ref_dying(false),
  1346. unsafe_referenced(false),
  1347. predelete_notified(false),
  1348. destructing_script_instance(false) {
  1349. }
  1350. CSharpInstance::~CSharpInstance() {
  1351. destructing_script_instance = true;
  1352. if (gchandle.is_valid()) {
  1353. if (!predelete_notified && !ref_dying) {
  1354. // This destructor is not called from the owners destructor.
  1355. // This could be being called from the owner's set_script_instance method,
  1356. // meaning this script is being replaced with another one. If this is the case,
  1357. // we must call Dispose here, because Dispose calls owner->set_script_instance(NULL)
  1358. // and that would mess up with the new script instance if called later.
  1359. MonoObject *mono_object = gchandle->get_target();
  1360. if (mono_object) {
  1361. MonoException *exc = NULL;
  1362. GDMonoUtils::dispose(mono_object, &exc);
  1363. if (exc) {
  1364. GDMonoUtils::set_pending_exception(exc);
  1365. }
  1366. }
  1367. }
  1368. gchandle->release(); // Make sure the gchandle is released
  1369. }
  1370. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1371. if (base_ref && !ref_dying && owner && unsafe_referenced) {
  1372. // The owner's script or script instance is being replaced (or removed)
  1373. // Transfer ownership to an "instance binding"
  1374. void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  1375. CRASH_COND(data == NULL);
  1376. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1377. CRASH_COND(!script_binding.inited);
  1378. bool die = _unreference_owner_unsafe();
  1379. CRASH_COND(die == true); // The "instance binding" should be holding a reference
  1380. }
  1381. if (script.is_valid() && owner) {
  1382. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1383. #ifdef DEBUG_ENABLED
  1384. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1385. Set<Object *>::Element *match = script->instances.find(owner);
  1386. CRASH_COND(!match);
  1387. script->instances.erase(match);
  1388. #else
  1389. script->instances.erase(owner);
  1390. #endif
  1391. }
  1392. }
  1393. #ifdef TOOLS_ENABLED
  1394. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1395. placeholders.erase(p_placeholder);
  1396. }
  1397. #endif
  1398. #ifdef TOOLS_ENABLED
  1399. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1400. if (base_cache.is_valid()) {
  1401. base_cache->_update_exports_values(values, propnames);
  1402. }
  1403. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1404. values[E->key()] = E->get();
  1405. }
  1406. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1407. propnames.push_back(E->get());
  1408. }
  1409. }
  1410. #endif
  1411. bool CSharpScript::_update_exports() {
  1412. #ifdef TOOLS_ENABLED
  1413. placeholder_fallback_enabled = true; // until proven otherwise
  1414. if (!valid)
  1415. return false;
  1416. bool changed = false;
  1417. if (exports_invalidated) {
  1418. exports_invalidated = false;
  1419. changed = true;
  1420. member_info.clear();
  1421. exported_members_cache.clear();
  1422. exported_members_defval_cache.clear();
  1423. // Here we create a temporary managed instance of the class to get the initial values
  1424. MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1425. if (!tmp_object) {
  1426. ERR_PRINT("Failed to create temporary MonoObject");
  1427. return false;
  1428. }
  1429. uint32_t tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed)
  1430. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1431. MonoException *ctor_exc = NULL;
  1432. ctor->invoke(tmp_object, NULL, &ctor_exc);
  1433. if (ctor_exc) {
  1434. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1435. tmp_object = NULL;
  1436. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1437. GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
  1438. return false;
  1439. }
  1440. GDMonoClass *top = script_class;
  1441. while (top && top != native) {
  1442. PropertyInfo prop_info;
  1443. bool exported;
  1444. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1445. for (int i = fields.size() - 1; i >= 0; i--) {
  1446. GDMonoField *field = fields[i];
  1447. if (_get_member_export(top, field, prop_info, exported)) {
  1448. StringName name = field->get_name();
  1449. if (exported) {
  1450. member_info[name] = prop_info;
  1451. exported_members_cache.push_front(prop_info);
  1452. if (tmp_object) {
  1453. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1454. }
  1455. } else {
  1456. member_info[name] = prop_info;
  1457. }
  1458. }
  1459. }
  1460. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1461. for (int i = properties.size() - 1; i >= 0; i--) {
  1462. GDMonoProperty *property = properties[i];
  1463. if (_get_member_export(top, property, prop_info, exported)) {
  1464. StringName name = property->get_name();
  1465. if (exported) {
  1466. member_info[name] = prop_info;
  1467. exported_members_cache.push_front(prop_info);
  1468. if (tmp_object) {
  1469. MonoException *exc = NULL;
  1470. MonoObject *ret = property->get_value(tmp_object, &exc);
  1471. if (exc) {
  1472. exported_members_defval_cache[name] = Variant();
  1473. GDMonoUtils::debug_print_unhandled_exception(exc);
  1474. } else {
  1475. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret);
  1476. }
  1477. }
  1478. } else {
  1479. member_info[name] = prop_info;
  1480. }
  1481. }
  1482. }
  1483. top = top->get_parent_class();
  1484. }
  1485. // Dispose the temporary managed instance
  1486. MonoException *exc = NULL;
  1487. GDMonoUtils::dispose(tmp_object, &exc);
  1488. if (exc) {
  1489. ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
  1490. GDMonoUtils::debug_print_unhandled_exception(exc);
  1491. }
  1492. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1493. tmp_object = NULL;
  1494. }
  1495. placeholder_fallback_enabled = false;
  1496. if (placeholders.size()) {
  1497. // Update placeholders if any
  1498. Map<StringName, Variant> values;
  1499. List<PropertyInfo> propnames;
  1500. _update_exports_values(values, propnames);
  1501. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1502. E->get()->update(propnames, values);
  1503. }
  1504. }
  1505. return changed;
  1506. #endif
  1507. return false;
  1508. }
  1509. void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
  1510. // no need to load the script's signals more than once
  1511. if (!signals_invalidated) {
  1512. return;
  1513. }
  1514. // make sure this classes signals are empty when loading for the first time
  1515. _signals.clear();
  1516. GDMonoClass *top = p_class;
  1517. while (top && top != p_native_class) {
  1518. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1519. for (int i = delegates.size() - 1; i >= 0; --i) {
  1520. Vector<Argument> parameters;
  1521. GDMonoClass *delegate = delegates[i];
  1522. if (_get_signal(top, delegate, parameters)) {
  1523. _signals[delegate->get_name()] = parameters;
  1524. }
  1525. }
  1526. top = top->get_parent_class();
  1527. }
  1528. signals_invalidated = false;
  1529. }
  1530. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1531. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1532. MonoType *raw_type = p_delegate->get_mono_type();
  1533. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1534. // Arguments are accessibles as arguments of .Invoke method
  1535. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1536. Vector<StringName> names;
  1537. Vector<ManagedType> types;
  1538. invoke->get_parameter_names(names);
  1539. invoke->get_parameter_types(types);
  1540. if (names.size() == types.size()) {
  1541. for (int i = 0; i < names.size(); ++i) {
  1542. Argument arg;
  1543. arg.name = names[i];
  1544. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1545. if (arg.type == Variant::NIL) {
  1546. ERR_PRINTS("Unknown type of signal parameter: " + arg.name + " in " + p_class->get_full_name());
  1547. return false;
  1548. }
  1549. params.push_back(arg);
  1550. }
  1551. return true;
  1552. }
  1553. }
  1554. }
  1555. return false;
  1556. }
  1557. #ifdef TOOLS_ENABLED
  1558. /**
  1559. * Returns false if there was an error, otherwise true.
  1560. * If there was an error, r_prop_info and r_exported are not assigned any value.
  1561. */
  1562. bool CSharpScript::_get_member_export(GDMonoClass *p_class, IMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) {
  1563. StringName name = p_member->get_name();
  1564. if (p_member->is_static()) {
  1565. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1566. ERR_PRINTS("Cannot export member because it is static: " + p_class->get_full_name() + "." + name.operator String());
  1567. return false;
  1568. }
  1569. if (member_info.has(name))
  1570. return false;
  1571. ManagedType type;
  1572. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
  1573. type = static_cast<GDMonoField *>(p_member)->get_type();
  1574. } else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1575. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1576. } else {
  1577. CRASH_NOW();
  1578. }
  1579. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1580. if (!p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
  1581. r_prop_info = PropertyInfo(variant_type, name.operator String(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1582. r_exported = false;
  1583. return true;
  1584. }
  1585. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1586. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1587. if (!property->has_getter() || !property->has_setter()) {
  1588. ERR_PRINTS("Cannot export property because it does not provide a getter or a setter: " + p_class->get_full_name() + "." + name.operator String());
  1589. return false;
  1590. }
  1591. }
  1592. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1593. PropertyHint hint = PROPERTY_HINT_NONE;
  1594. String hint_string;
  1595. if (variant_type == Variant::NIL) {
  1596. ERR_PRINTS("Unknown type of exported member: " + p_class->get_full_name() + "." + name.operator String());
  1597. return false;
  1598. } else if (variant_type == Variant::INT && type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(type.type_class->get_mono_ptr())) {
  1599. variant_type = Variant::INT;
  1600. hint = PROPERTY_HINT_ENUM;
  1601. Vector<MonoClassField *> fields = type.type_class->get_enum_fields();
  1602. MonoType *enum_basetype = mono_class_enum_basetype(type.type_class->get_mono_ptr());
  1603. String name_only_hint_string;
  1604. // True: enum Foo { Bar, Baz, Quux }
  1605. // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
  1606. // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
  1607. bool uses_default_values = true;
  1608. for (int i = 0; i < fields.size(); i++) {
  1609. MonoClassField *field = fields[i];
  1610. if (i > 0) {
  1611. hint_string += ",";
  1612. name_only_hint_string += ",";
  1613. }
  1614. String enum_field_name = mono_field_get_name(field);
  1615. hint_string += enum_field_name;
  1616. name_only_hint_string += enum_field_name;
  1617. // TODO:
  1618. // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
  1619. // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
  1620. MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL);
  1621. if (val_obj == NULL) {
  1622. ERR_PRINTS("Failed to get '" + enum_field_name + "' constant enum value of exported member: " +
  1623. p_class->get_full_name() + "." + name.operator String());
  1624. return false;
  1625. }
  1626. bool r_error;
  1627. uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
  1628. if (r_error) {
  1629. ERR_PRINTS("Failed to unbox '" + enum_field_name + "' constant enum value of exported member: " +
  1630. p_class->get_full_name() + "." + name.operator String());
  1631. return false;
  1632. }
  1633. if (val != i) {
  1634. uses_default_values = false;
  1635. }
  1636. hint_string += ":";
  1637. hint_string += String::num_uint64(val);
  1638. }
  1639. if (uses_default_values) {
  1640. // If we use the format NAME:VAL, that's what the editor displays.
  1641. // That's annoying if the user is not using custom values for the enum constants.
  1642. // This may not be needed in the future if the editor is changed to not display values.
  1643. hint_string = name_only_hint_string;
  1644. }
  1645. } else if (variant_type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(type.type_class)) {
  1646. hint = PROPERTY_HINT_RESOURCE_TYPE;
  1647. hint_string = NATIVE_GDMONOCLASS_NAME(type.type_class);
  1648. } else {
  1649. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1650. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1651. }
  1652. r_prop_info = PropertyInfo(variant_type, name.operator String(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1653. r_exported = true;
  1654. return true;
  1655. }
  1656. #endif
  1657. void CSharpScript::_clear() {
  1658. tool = false;
  1659. valid = false;
  1660. base = NULL;
  1661. native = NULL;
  1662. script_class = NULL;
  1663. }
  1664. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1665. if (unlikely(GDMono::get_singleton() == NULL)) {
  1666. // Probably not the best error but eh.
  1667. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1668. return Variant();
  1669. }
  1670. GDMonoClass *top = script_class;
  1671. while (top && top != native) {
  1672. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1673. if (method && method->is_static()) {
  1674. MonoObject *result = method->invoke(NULL, p_args);
  1675. if (result) {
  1676. return GDMonoMarshal::mono_object_to_variant(result);
  1677. } else {
  1678. return Variant();
  1679. }
  1680. }
  1681. top = top->get_parent_class();
  1682. }
  1683. // No static method found. Try regular instance calls
  1684. return Script::call(p_method, p_args, p_argcount, r_error);
  1685. }
  1686. void CSharpScript::_resource_path_changed() {
  1687. String path = get_path();
  1688. if (!path.empty()) {
  1689. name = get_path().get_file().get_basename();
  1690. }
  1691. }
  1692. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1693. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1694. r_ret = get_source_code();
  1695. return true;
  1696. }
  1697. return false;
  1698. }
  1699. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1700. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1701. set_source_code(p_value);
  1702. reload();
  1703. return true;
  1704. }
  1705. return false;
  1706. }
  1707. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1708. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  1709. }
  1710. void CSharpScript::_bind_methods() {
  1711. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
  1712. }
  1713. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
  1714. // This method should not fail
  1715. CRASH_COND(!p_class);
  1716. // TODO: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
  1717. Ref<CSharpScript> script = memnew(CSharpScript);
  1718. script->name = p_class->get_name();
  1719. script->script_class = p_class;
  1720. script->native = p_native;
  1721. CRASH_COND(script->native == NULL);
  1722. GDMonoClass *base = script->script_class->get_parent_class();
  1723. if (base != script->native)
  1724. script->base = base;
  1725. #ifdef DEBUG_ENABLED
  1726. // For debug builds, we must fetch from all native base methods as well.
  1727. // Native base methods must be fetched before the current class.
  1728. // Not needed if the script class itself is a native class.
  1729. if (script->script_class != script->native) {
  1730. GDMonoClass *native_top = script->native;
  1731. while (native_top) {
  1732. native_top->fetch_methods_with_godot_api_checks(script->native);
  1733. if (native_top == CACHED_CLASS(GodotObject))
  1734. break;
  1735. native_top = native_top->get_parent_class();
  1736. }
  1737. }
  1738. #endif
  1739. script->script_class->fetch_methods_with_godot_api_checks(script->native);
  1740. // Need to fetch method from base classes as well
  1741. GDMonoClass *top = script->script_class;
  1742. while (top && top != script->native) {
  1743. top->fetch_methods_with_godot_api_checks(script->native);
  1744. top = top->get_parent_class();
  1745. }
  1746. script->load_script_signals(script->script_class, script->native);
  1747. return script;
  1748. }
  1749. bool CSharpScript::can_instance() const {
  1750. #ifdef TOOLS_ENABLED
  1751. if (Engine::get_singleton()->is_editor_hint()) {
  1752. if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  1753. if (_create_project_solution_if_needed()) {
  1754. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1755. "Compile",
  1756. ProjectSettings::get_singleton()->globalize_path(get_path()));
  1757. } else {
  1758. ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created.");
  1759. }
  1760. }
  1761. }
  1762. #endif
  1763. #ifdef TOOLS_ENABLED
  1764. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  1765. #else
  1766. bool extra_cond = true;
  1767. #endif
  1768. // FIXME Need to think this through better.
  1769. // For tool scripts, this will never fire if the class is not found. That's because we
  1770. // don't know if it's a tool script if we can't find the class to access the attributes.
  1771. if (extra_cond && !script_class) {
  1772. if (GDMono::get_singleton()->get_project_assembly() == NULL) {
  1773. // The project assembly is not loaded
  1774. ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path());
  1775. ERR_FAIL_V(NULL);
  1776. } else {
  1777. // The project assembly is loaded, but the class could not found
  1778. ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path());
  1779. ERR_FAIL_V(NULL);
  1780. }
  1781. }
  1782. return valid && extra_cond;
  1783. }
  1784. StringName CSharpScript::get_instance_base_type() const {
  1785. if (native)
  1786. return native->get_name();
  1787. else
  1788. return StringName();
  1789. }
  1790. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  1791. /* STEP 1, CREATE */
  1792. Ref<Reference> ref;
  1793. if (p_isref) {
  1794. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  1795. ref = Ref<Reference>(static_cast<Reference *>(p_owner));
  1796. }
  1797. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  1798. if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) {
  1799. void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  1800. CRASH_COND(data == NULL);
  1801. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1802. if (script_binding.inited && script_binding.gchandle.is_valid()) {
  1803. MonoObject *mono_object = script_binding.gchandle->get_target();
  1804. if (mono_object) {
  1805. MonoException *exc = NULL;
  1806. GDMonoUtils::dispose(mono_object, &exc);
  1807. if (exc) {
  1808. GDMonoUtils::set_pending_exception(exc);
  1809. }
  1810. }
  1811. script_binding.inited = false;
  1812. }
  1813. }
  1814. CSharpInstance *instance = memnew(CSharpInstance);
  1815. instance->base_ref = p_isref;
  1816. instance->script = Ref<CSharpScript>(this);
  1817. instance->owner = p_owner;
  1818. instance->owner->set_script_instance(instance);
  1819. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1820. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1821. if (!mono_object) {
  1822. // Important to clear this before destroying the script instance here
  1823. instance->script = Ref<CSharpScript>();
  1824. instance->owner = NULL;
  1825. bool die = instance->_unreference_owner_unsafe();
  1826. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  1827. CRASH_COND(die == true);
  1828. p_owner->set_script_instance(NULL);
  1829. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1830. ERR_EXPLAIN("Failed to allocate memory for the object");
  1831. ERR_FAIL_V(NULL);
  1832. }
  1833. // Tie managed to unmanaged
  1834. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  1835. if (instance->base_ref)
  1836. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1837. {
  1838. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1839. instances.insert(instance->owner);
  1840. }
  1841. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  1842. // Construct
  1843. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  1844. ctor->invoke(mono_object, p_args);
  1845. /* STEP 3, PARTY */
  1846. //@TODO make thread safe
  1847. return instance;
  1848. }
  1849. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1850. if (!valid) {
  1851. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1852. return Variant();
  1853. }
  1854. r_error.error = Variant::CallError::CALL_OK;
  1855. REF ref;
  1856. Object *owner = NULL;
  1857. ERR_FAIL_NULL_V(native, Variant());
  1858. owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  1859. Reference *r = Object::cast_to<Reference>(owner);
  1860. if (r) {
  1861. ref = REF(r);
  1862. }
  1863. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  1864. if (!instance) {
  1865. if (ref.is_null()) {
  1866. memdelete(owner); //no owner, sorry
  1867. }
  1868. return Variant();
  1869. }
  1870. if (ref.is_valid()) {
  1871. return ref;
  1872. } else {
  1873. return owner;
  1874. }
  1875. }
  1876. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1877. #ifdef DEBUG_ENABLED
  1878. CRASH_COND(!valid);
  1879. #endif
  1880. if (native) {
  1881. String native_name = native->get_name();
  1882. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1883. if (ScriptDebugger::get_singleton()) {
  1884. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  1885. }
  1886. ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  1887. ERR_FAIL_V(NULL);
  1888. }
  1889. }
  1890. Variant::CallError unchecked_error;
  1891. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  1892. }
  1893. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1894. #ifdef TOOLS_ENABLED
  1895. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1896. placeholders.insert(si);
  1897. _update_exports();
  1898. return si;
  1899. #else
  1900. return NULL;
  1901. #endif
  1902. }
  1903. bool CSharpScript::instance_has(const Object *p_this) const {
  1904. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1905. return instances.has((Object *)p_this);
  1906. }
  1907. bool CSharpScript::has_source_code() const {
  1908. return !source.empty();
  1909. }
  1910. String CSharpScript::get_source_code() const {
  1911. return source;
  1912. }
  1913. void CSharpScript::set_source_code(const String &p_code) {
  1914. if (source == p_code)
  1915. return;
  1916. source = p_code;
  1917. #ifdef TOOLS_ENABLED
  1918. source_changed_cache = true;
  1919. #endif
  1920. }
  1921. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  1922. if (!script_class)
  1923. return;
  1924. // TODO: Filter out things unsuitable for explicit calls, like constructors.
  1925. const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
  1926. for (int i = 0; i < methods.size(); ++i) {
  1927. p_list->push_back(methods[i]->get_method_info());
  1928. }
  1929. }
  1930. bool CSharpScript::has_method(const StringName &p_method) const {
  1931. if (!script_class)
  1932. return false;
  1933. return script_class->has_fetched_method_unknown_params(p_method);
  1934. }
  1935. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  1936. if (!script_class)
  1937. return MethodInfo();
  1938. GDMonoClass *top = script_class;
  1939. while (top && top != native) {
  1940. GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
  1941. if (params) {
  1942. return params->get_method_info();
  1943. }
  1944. top = top->get_parent_class();
  1945. }
  1946. return MethodInfo();
  1947. }
  1948. Error CSharpScript::reload(bool p_keep_state) {
  1949. bool has_instances;
  1950. {
  1951. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1952. has_instances = instances.size();
  1953. }
  1954. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  1955. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  1956. if (project_assembly) {
  1957. const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path());
  1958. if (script_metadata_var) {
  1959. Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"];
  1960. const Variant *namespace_ = script_metadata.getptr("namespace");
  1961. const Variant *class_name = script_metadata.getptr("class_name");
  1962. ERR_FAIL_NULL_V(namespace_, ERR_BUG);
  1963. ERR_FAIL_NULL_V(class_name, ERR_BUG);
  1964. GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
  1965. if (klass) {
  1966. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass);
  1967. ERR_FAIL_COND_V(!obj_type, ERR_BUG);
  1968. script_class = klass;
  1969. }
  1970. } else {
  1971. // Missing script metadata. Fallback to legacy method
  1972. script_class = project_assembly->get_object_derived_class(name);
  1973. }
  1974. valid = script_class != NULL;
  1975. if (script_class) {
  1976. #ifdef DEBUG_ENABLED
  1977. print_verbose("Found class " + script_class->get_namespace() + "." + script_class->get_name() + " for script " + get_path());
  1978. #endif
  1979. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  1980. native = GDMonoUtils::get_class_native_base(script_class);
  1981. CRASH_COND(native == NULL);
  1982. GDMonoClass *base_class = script_class->get_parent_class();
  1983. if (base_class != native)
  1984. base = base_class;
  1985. #ifdef DEBUG_ENABLED
  1986. // For debug builds, we must fetch from all native base methods as well.
  1987. // Native base methods must be fetched before the current class.
  1988. // Not needed if the script class itself is a native class.
  1989. if (script_class != native) {
  1990. GDMonoClass *native_top = native;
  1991. while (native_top) {
  1992. native_top->fetch_methods_with_godot_api_checks(native);
  1993. if (native_top == CACHED_CLASS(GodotObject))
  1994. break;
  1995. native_top = native_top->get_parent_class();
  1996. }
  1997. }
  1998. #endif
  1999. script_class->fetch_methods_with_godot_api_checks(native);
  2000. // Need to fetch method from base classes as well
  2001. GDMonoClass *top = script_class;
  2002. while (top && top != native) {
  2003. top->fetch_methods_with_godot_api_checks(native);
  2004. top = top->get_parent_class();
  2005. }
  2006. load_script_signals(script_class, native);
  2007. }
  2008. return OK;
  2009. }
  2010. return ERR_FILE_MISSING_DEPENDENCIES;
  2011. }
  2012. ScriptLanguage *CSharpScript::get_language() const {
  2013. return CSharpLanguage::get_singleton();
  2014. }
  2015. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2016. #ifdef TOOLS_ENABLED
  2017. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  2018. if (E) {
  2019. r_value = E->get();
  2020. return true;
  2021. }
  2022. if (base_cache.is_valid()) {
  2023. return base_cache->get_property_default_value(p_property, r_value);
  2024. }
  2025. #endif
  2026. return false;
  2027. }
  2028. void CSharpScript::update_exports() {
  2029. #ifdef TOOLS_ENABLED
  2030. _update_exports();
  2031. #endif
  2032. }
  2033. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2034. if (_signals.has(p_signal))
  2035. return true;
  2036. return false;
  2037. }
  2038. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2039. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  2040. MethodInfo mi;
  2041. mi.name = E->key();
  2042. for (int i = 0; i < E->get().size(); i++) {
  2043. PropertyInfo arg;
  2044. arg.name = E->get()[i].name;
  2045. mi.arguments.push_back(arg);
  2046. }
  2047. r_signals->push_back(mi);
  2048. }
  2049. }
  2050. Ref<Script> CSharpScript::get_base_script() const {
  2051. // TODO search in metadata file once we have it, not important any way?
  2052. return Ref<Script>();
  2053. }
  2054. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  2055. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  2056. p_list->push_back(E->value());
  2057. }
  2058. }
  2059. int CSharpScript::get_member_line(const StringName &p_member) const {
  2060. // TODO omnisharp
  2061. return -1;
  2062. }
  2063. Error CSharpScript::load_source_code(const String &p_path) {
  2064. Error ferr = read_all_file_utf8(p_path, source);
  2065. if (ferr != OK) {
  2066. if (ferr == ERR_INVALID_DATA) {
  2067. ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
  2068. }
  2069. ERR_FAIL_V(ferr);
  2070. }
  2071. #ifdef TOOLS_ENABLED
  2072. source_changed_cache = true;
  2073. #endif
  2074. return OK;
  2075. }
  2076. StringName CSharpScript::get_script_name() const {
  2077. return name;
  2078. }
  2079. CSharpScript::CSharpScript() :
  2080. script_list(this) {
  2081. _clear();
  2082. #ifdef TOOLS_ENABLED
  2083. source_changed_cache = false;
  2084. placeholder_fallback_enabled = false;
  2085. exports_invalidated = true;
  2086. #endif
  2087. signals_invalidated = true;
  2088. _resource_path_changed();
  2089. #ifdef DEBUG_ENABLED
  2090. {
  2091. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2092. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2093. }
  2094. #endif
  2095. }
  2096. CSharpScript::~CSharpScript() {
  2097. #ifdef DEBUG_ENABLED
  2098. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2099. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2100. #endif
  2101. }
  2102. /*************** RESOURCE ***************/
  2103. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  2104. if (r_error)
  2105. *r_error = ERR_FILE_CANT_OPEN;
  2106. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2107. CSharpScript *script = memnew(CSharpScript);
  2108. Ref<CSharpScript> scriptres(script);
  2109. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2110. Error err = script->load_source_code(p_path);
  2111. ERR_FAIL_COND_V(err != OK, RES());
  2112. #endif
  2113. script->set_path(p_original_path);
  2114. #ifndef TOOLS_ENABLED
  2115. #ifdef DEBUG_ENABLED
  2116. // User is responsible for thread attach/detach
  2117. ERR_EXPLAIN("Thread is not attached");
  2118. CRASH_COND(mono_domain_get() == NULL);
  2119. #endif
  2120. #endif
  2121. #ifdef TOOLS_ENABLED
  2122. if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) {
  2123. CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
  2124. // Thread is not attached, but we will make an exception in this case
  2125. // because this may be called by one of the editor's worker threads.
  2126. // Attach this thread temporarily to reload the script.
  2127. if (SCRIPTS_DOMAIN) {
  2128. MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
  2129. CRASH_COND(mono_thread == NULL);
  2130. script->reload();
  2131. mono_thread_detach(mono_thread);
  2132. }
  2133. } else { // just reload it normally
  2134. #endif
  2135. script->reload();
  2136. #ifdef TOOLS_ENABLED
  2137. }
  2138. #endif
  2139. if (r_error)
  2140. *r_error = OK;
  2141. return scriptres;
  2142. }
  2143. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2144. p_extensions->push_back("cs");
  2145. }
  2146. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2147. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2148. }
  2149. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2150. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2151. }
  2152. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  2153. Ref<CSharpScript> sqscr = p_resource;
  2154. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2155. String source = sqscr->get_source_code();
  2156. #ifdef TOOLS_ENABLED
  2157. if (!FileAccess::exists(p_path)) {
  2158. // The file does not yet exists, let's assume the user just created this script
  2159. if (_create_project_solution_if_needed()) {
  2160. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2161. "Compile",
  2162. ProjectSettings::get_singleton()->globalize_path(p_path));
  2163. } else {
  2164. ERR_PRINTS("Failed to create C# project");
  2165. ERR_PRINTS("Cannot add " + p_path + " to the C# project");
  2166. }
  2167. }
  2168. #endif
  2169. Error err;
  2170. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2171. ERR_FAIL_COND_V(err, err);
  2172. file->store_string(source);
  2173. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2174. memdelete(file);
  2175. return ERR_CANT_CREATE;
  2176. }
  2177. file->close();
  2178. memdelete(file);
  2179. #ifdef TOOLS_ENABLED
  2180. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2181. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2182. }
  2183. #endif
  2184. return OK;
  2185. }
  2186. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  2187. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2188. p_extensions->push_back("cs");
  2189. }
  2190. }
  2191. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  2192. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  2193. }
  2194. CSharpLanguage::StringNameCache::StringNameCache() {
  2195. _signal_callback = StaticCString::create("_signal_callback");
  2196. _set = StaticCString::create("_set");
  2197. _get = StaticCString::create("_get");
  2198. _notification = StaticCString::create("_notification");
  2199. _script_source = StaticCString::create("script/source");
  2200. dotctor = StaticCString::create(".ctor");
  2201. }