csharp_script.cpp 78 KB

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