csharp_script.cpp 77 KB

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