csharp_script.cpp 101 KB

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