Compiler.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.CodeDom.Compiler;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using Microsoft.CSharp;
  33. using Microsoft.JScript;
  34. using Microsoft.VisualBasic;
  35. using OpenSim.Region.Environment.Interfaces;
  36. namespace OpenSim.Region.ScriptEngine.XEngine
  37. {
  38. public class Compiler
  39. {
  40. private static readonly log4net.ILog m_log
  41. = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  42. // * Uses "LSL2Converter" to convert LSL to C# if necessary.
  43. // * Compiles C#-code into an assembly
  44. // * Returns assembly name ready for AppDomain load.
  45. //
  46. // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
  47. //
  48. internal enum enumCompileType
  49. {
  50. lsl = 0,
  51. cs = 1,
  52. vb = 2,
  53. js = 3
  54. }
  55. /// <summary>
  56. /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
  57. /// </summary>
  58. public int LinesToRemoveOnError = 3;
  59. private enumCompileType DefaultCompileLanguage;
  60. private bool WriteScriptSourceToDebugFile;
  61. private bool CompileWithDebugInformation;
  62. private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  63. private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  64. private string FilePrefix;
  65. private string ScriptEnginesPath = "ScriptEngines";
  66. private static LSL2CSConverter LSL_Converter = new LSL2CSConverter();
  67. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  68. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  69. private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
  70. private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  71. private static UInt64 scriptCompileCounter = 0; // And a counter
  72. public XEngine m_scriptEngine;
  73. public Compiler(XEngine scriptEngine)
  74. {
  75. m_scriptEngine = scriptEngine;
  76. ReadConfig();
  77. }
  78. public bool in_startup = true;
  79. public void ReadConfig()
  80. {
  81. // Get some config
  82. WriteScriptSourceToDebugFile = m_scriptEngine.ScriptConfigSource.GetBoolean("WriteScriptSourceToDebugFile", true);
  83. CompileWithDebugInformation = m_scriptEngine.ScriptConfigSource.GetBoolean("CompileWithDebugInformation", true);
  84. // Get file prefix from scriptengine name and make it file system safe:
  85. FilePrefix = m_scriptEngine.ScriptEngineName;
  86. foreach (char c in Path.GetInvalidFileNameChars())
  87. {
  88. FilePrefix = FilePrefix.Replace(c, '_');
  89. }
  90. // First time we start? Delete old files
  91. if (in_startup)
  92. {
  93. in_startup = false;
  94. DeleteOldFiles();
  95. }
  96. // Map name and enum type of our supported languages
  97. LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
  98. LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
  99. LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
  100. LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
  101. // Allowed compilers
  102. string allowComp = m_scriptEngine.ScriptConfigSource.GetString("AllowedCompilers", "lsl,cs,vb,js");
  103. AllowedCompilers.Clear();
  104. #if DEBUG
  105. m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Allowed languages: " + allowComp);
  106. #endif
  107. foreach (string strl in allowComp.Split(','))
  108. {
  109. string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
  110. if (!LanguageMapping.ContainsKey(strlan))
  111. {
  112. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  113. }
  114. else
  115. {
  116. #if DEBUG
  117. //m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  118. #endif
  119. }
  120. AllowedCompilers.Add(strlan, true);
  121. }
  122. if (AllowedCompilers.Count == 0)
  123. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
  124. // Default language
  125. string defaultCompileLanguage = m_scriptEngine.ScriptConfigSource.GetString("DefaultCompileLanguage", "lsl").ToLower();
  126. // Is this language recognized at all?
  127. if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
  128. {
  129. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " +
  130. "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
  131. defaultCompileLanguage = "lsl";
  132. }
  133. // Is this language in allow-list?
  134. if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
  135. {
  136. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " +
  137. "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
  138. }
  139. else
  140. {
  141. #if DEBUG
  142. // m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: " +
  143. // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
  144. #endif
  145. // LANGUAGE IS IN ALLOW-LIST
  146. DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
  147. }
  148. // We now have an allow-list, a mapping list, and a default language
  149. }
  150. /// <summary>
  151. /// Delete old script files
  152. /// </summary>
  153. private void DeleteOldFiles()
  154. {
  155. // CREATE FOLDER IF IT DOESNT EXIST
  156. if (!Directory.Exists(ScriptEnginesPath))
  157. {
  158. try
  159. {
  160. Directory.CreateDirectory(ScriptEnginesPath);
  161. }
  162. catch (Exception ex)
  163. {
  164. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
  165. }
  166. }
  167. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  168. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  169. {
  170. try
  171. {
  172. Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
  173. m_scriptEngine.World.RegionInfo.RegionID.ToString()));
  174. }
  175. catch (Exception ex)
  176. {
  177. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
  178. m_scriptEngine.World.RegionInfo.RegionID.ToString())+ "\": " + ex.ToString());
  179. }
  180. }
  181. foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
  182. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  183. {
  184. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: FILE FOUND: " + file);
  185. if (file.ToLower().StartsWith(FilePrefix + "_compiled_") ||
  186. file.ToLower().StartsWith(FilePrefix + "_source_"))
  187. {
  188. try
  189. {
  190. File.Delete(file);
  191. }
  192. catch (Exception ex)
  193. {
  194. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  195. }
  196. }
  197. }
  198. }
  199. ////private ICodeCompiler icc = codeProvider.CreateCompiler();
  200. //public string CompileFromFile(string LSOFileName)
  201. //{
  202. // switch (Path.GetExtension(LSOFileName).ToLower())
  203. // {
  204. // case ".txt":
  205. // case ".lsl":
  206. // Common.ScriptEngineBase.Common.SendToDebug("Source code is LSL, converting to CS");
  207. // return CompileFromLSLText(File.ReadAllText(LSOFileName));
  208. // case ".cs":
  209. // Common.ScriptEngineBase.Common.SendToDebug("Source code is CS");
  210. // return CompileFromCSText(File.ReadAllText(LSOFileName));
  211. // default:
  212. // throw new Exception("Unknown script type.");
  213. // }
  214. //}
  215. /// <summary>
  216. /// Converts script from LSL to CS and calls CompileFromCSText
  217. /// </summary>
  218. /// <param name="Script">LSL script</param>
  219. /// <returns>Filename to .dll assembly</returns>
  220. public string PerformScriptCompile(string Script, string asset)
  221. {
  222. string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
  223. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  224. FilePrefix + "_compiled_" + asset + ".dll"));
  225. // string OutFile = Path.Combine(ScriptEnginesPath,
  226. // FilePrefix + "_compiled_" + asset + ".dll");
  227. if(File.Exists(OutFile))
  228. return OutFile;
  229. if (!Directory.Exists(ScriptEnginesPath))
  230. {
  231. try
  232. {
  233. Directory.CreateDirectory(ScriptEnginesPath);
  234. }
  235. catch (Exception ex)
  236. {
  237. }
  238. }
  239. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  240. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  241. {
  242. try
  243. {
  244. Directory.CreateDirectory(ScriptEnginesPath);
  245. }
  246. catch (Exception ex)
  247. {
  248. }
  249. }
  250. enumCompileType l = DefaultCompileLanguage;
  251. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  252. l = enumCompileType.cs;
  253. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  254. {
  255. l = enumCompileType.vb;
  256. // We need to remove //vb, it won't compile with that
  257. Script = Script.Substring(4, Script.Length - 4);
  258. }
  259. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  260. l = enumCompileType.lsl;
  261. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  262. l = enumCompileType.js;
  263. if (!AllowedCompilers.ContainsKey(l.ToString()))
  264. {
  265. // Not allowed to compile to this language!
  266. string errtext = String.Empty;
  267. errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  268. throw new Exception(errtext);
  269. }
  270. string compileScript = Script;
  271. if (l == enumCompileType.lsl)
  272. {
  273. // Its LSL, convert it to C#
  274. compileScript = LSL_Converter.Convert(Script);
  275. l = enumCompileType.cs;
  276. }
  277. // Insert additional assemblies here
  278. //ADAM: Disabled for the moment until it's working right.
  279. bool enableCommanderLSL = false;
  280. if (enableCommanderLSL == true && l == enumCompileType.cs)
  281. {
  282. foreach (KeyValuePair<string,
  283. ICommander> com
  284. in m_scriptEngine.World.GetCommanders())
  285. {
  286. compileScript = com.Value.GenerateRuntimeAPI() + compileScript;
  287. }
  288. }
  289. // End of insert
  290. switch (l)
  291. {
  292. case enumCompileType.cs:
  293. compileScript = CreateCSCompilerScript(compileScript);
  294. break;
  295. case enumCompileType.vb:
  296. compileScript = CreateVBCompilerScript(compileScript);
  297. break;
  298. case enumCompileType.js:
  299. compileScript = CreateJSCompilerScript(compileScript);
  300. break;
  301. }
  302. // m_log.Debug("[ScriptEngine.DotNetEngine]: Preparing to compile the following LSL to C# translated code");
  303. // m_log.Debug("");
  304. // m_log.Debug(compileScript);
  305. return CompileFromDotNetText(compileScript, l, asset);
  306. }
  307. private static string CreateJSCompilerScript(string compileScript)
  308. {
  309. compileScript = String.Empty +
  310. "import OpenSim.Region.ScriptEngine.XEngine.Script; import System.Collections.Generic;\r\n" +
  311. "package SecondLife {\r\n" +
  312. "class Script extends OpenSim.Region.ScriptEngine.XEngine.Script.BuiltIn_Commands_BaseClass { \r\n" +
  313. compileScript +
  314. "} }\r\n";
  315. return compileScript;
  316. }
  317. private static string CreateCSCompilerScript(string compileScript)
  318. {
  319. compileScript = String.Empty +
  320. "using OpenSim.Region.ScriptEngine.XEngine.Script; using System.Collections.Generic;\r\n" +
  321. String.Empty + "namespace SecondLife { " +
  322. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.XEngine.Script.BuiltIn_Commands_BaseClass { \r\n" +
  323. @"public Script() { } " +
  324. compileScript +
  325. "} }\r\n";
  326. return compileScript;
  327. }
  328. private static string CreateVBCompilerScript(string compileScript)
  329. {
  330. compileScript = String.Empty +
  331. "Imports OpenSim.Region.ScriptEngine.XEngine.Script: Imports System.Collections.Generic: " +
  332. String.Empty + "NameSpace SecondLife:" +
  333. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.XEngine.Script.BuiltIn_Commands_BaseClass: " +
  334. "\r\nPublic Sub New()\r\nEnd Sub: " +
  335. compileScript +
  336. ":End Class :End Namespace\r\n";
  337. return compileScript;
  338. }
  339. /// <summary>
  340. /// Compile .NET script to .Net assembly (.dll)
  341. /// </summary>
  342. /// <param name="Script">CS script</param>
  343. /// <returns>Filename to .dll assembly</returns>
  344. internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset)
  345. {
  346. string ext = "." + lang.ToString();
  347. // Output assembly name
  348. scriptCompileCounter++;
  349. string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
  350. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  351. FilePrefix + "_compiled_" + asset + ".dll"));
  352. #if DEBUG
  353. // m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Starting compile of \"" + OutFile + "\".");
  354. #endif
  355. try
  356. {
  357. File.Delete(OutFile);
  358. }
  359. catch (Exception e) // NOTLEGIT - Should be just catching FileIOException
  360. {
  361. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  362. throw new Exception("Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  363. }
  364. //string OutFile = Path.Combine("ScriptEngines", "SecondLife.Script.dll");
  365. // DEBUG - write source to disk
  366. if (WriteScriptSourceToDebugFile)
  367. {
  368. string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(OutFile) + ext;
  369. try
  370. {
  371. File.WriteAllText(
  372. Path.Combine("ScriptEngines", srcFileName),
  373. Script);
  374. }
  375. catch (Exception ex) // NOTLEGIT - Should be just catching FileIOException
  376. {
  377. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception while trying to write script source to file \"" + srcFileName + "\": " + ex.ToString());
  378. }
  379. }
  380. // Do actual compile
  381. CompilerParameters parameters = new CompilerParameters();
  382. parameters.IncludeDebugInformation = true;
  383. // Add all available assemblies
  384. // foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
  385. // {
  386. // Console.WriteLine("Adding assembly: " + asm.Location);
  387. // parameters.ReferencedAssemblies.Add(asm.Location);
  388. // }
  389. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  390. string rootPathSE = Path.GetDirectoryName(GetType().Assembly.Location);
  391. //Console.WriteLine("Assembly location: " + rootPath);
  392. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.XEngine.Script.dll"));
  393. // parameters.ReferencedAssemblies.Add(Path.Combine(rootPathSE, "OpenSim.Region.ScriptEngine.XEngine.dll"));
  394. //parameters.ReferencedAssemblies.Add("OpenSim.Region.Environment");
  395. parameters.GenerateExecutable = false;
  396. parameters.OutputAssembly = OutFile;
  397. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  398. //parameters.WarningLevel = 1; // Should be 4?
  399. parameters.TreatWarningsAsErrors = false;
  400. //Console.WriteLine(Script);
  401. CompilerResults results;
  402. switch (lang)
  403. {
  404. case enumCompileType.vb:
  405. results = VBcodeProvider.CompileAssemblyFromSource(parameters, Script);
  406. break;
  407. case enumCompileType.cs:
  408. results = CScodeProvider.CompileAssemblyFromSource(parameters, Script);
  409. break;
  410. case enumCompileType.js:
  411. results = JScodeProvider.CompileAssemblyFromSource(parameters, Script);
  412. break;
  413. default:
  414. throw new Exception("Compiler is not able to recongnize language type \"" + lang.ToString() + "\"");
  415. }
  416. // Check result
  417. // Go through errors
  418. //
  419. // WARNINGS AND ERRORS
  420. //
  421. if (results.Errors.Count > 0)
  422. {
  423. string errtext = String.Empty;
  424. foreach (CompilerError CompErr in results.Errors)
  425. {
  426. errtext += "Line number " + (CompErr.Line - LinesToRemoveOnError) +
  427. ", Error Number: " + CompErr.ErrorNumber +
  428. ", '" + CompErr.ErrorText + "'\r\n";
  429. }
  430. if (!File.Exists(OutFile))
  431. {
  432. throw new Exception(errtext);
  433. }
  434. }
  435. //
  436. // NO ERRORS, BUT NO COMPILED FILE
  437. //
  438. if (!File.Exists(OutFile))
  439. {
  440. string errtext = String.Empty;
  441. errtext += "No compile error. But not able to locate compiled file.";
  442. throw new Exception(errtext);
  443. }
  444. return OutFile;
  445. }
  446. }
  447. }