csharp_script.cpp 106 KB

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