Compiler.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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.DotNetEngine.Compiler.LSL
  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 bool CleanUpOldScriptsOnStartup;
  63. private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  64. private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  65. private string FilePrefix;
  66. private string ScriptEnginesPath = "ScriptEngines";
  67. private static LSL2CSConverter LSL_Converter = new LSL2CSConverter();
  68. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  69. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  70. private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
  71. private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  72. private static UInt64 scriptCompileCounter = 0; // And a counter
  73. public Common.ScriptEngineBase.ScriptEngine m_scriptEngine;
  74. public Compiler(Common.ScriptEngineBase.ScriptEngine scriptEngine)
  75. {
  76. m_scriptEngine = scriptEngine;
  77. ReadConfig();
  78. }
  79. public bool in_startup = true;
  80. public void ReadConfig()
  81. {
  82. // Get some config
  83. WriteScriptSourceToDebugFile = m_scriptEngine.ScriptConfigSource.GetBoolean("WriteScriptSourceToDebugFile", true);
  84. CompileWithDebugInformation = m_scriptEngine.ScriptConfigSource.GetBoolean("CompileWithDebugInformation", true);
  85. CleanUpOldScriptsOnStartup = m_scriptEngine.ScriptConfigSource.GetBoolean("CleanUpOldScriptsOnStartup", true);
  86. // Get file prefix from scriptengine name and make it file system safe:
  87. FilePrefix = m_scriptEngine.ScriptEngineName;
  88. foreach (char c in Path.GetInvalidFileNameChars())
  89. {
  90. FilePrefix = FilePrefix.Replace(c, '_');
  91. }
  92. // First time we start? Delete old files
  93. if (in_startup)
  94. {
  95. in_startup = false;
  96. DeleteOldFiles();
  97. }
  98. // Map name and enum type of our supported languages
  99. LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
  100. LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
  101. LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
  102. LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
  103. // Allowed compilers
  104. string allowComp = m_scriptEngine.ScriptConfigSource.GetString("AllowedCompilers", "lsl,cs,vb,js");
  105. AllowedCompilers.Clear();
  106. #if DEBUG
  107. m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Allowed languages: " + allowComp);
  108. #endif
  109. foreach (string strl in allowComp.Split(','))
  110. {
  111. string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
  112. if (!LanguageMapping.ContainsKey(strlan))
  113. {
  114. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  115. }
  116. else
  117. {
  118. #if DEBUG
  119. //m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  120. #endif
  121. }
  122. AllowedCompilers.Add(strlan, true);
  123. }
  124. if (AllowedCompilers.Count == 0)
  125. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
  126. // Default language
  127. string defaultCompileLanguage = m_scriptEngine.ScriptConfigSource.GetString("DefaultCompileLanguage", "lsl").ToLower();
  128. // Is this language recognized at all?
  129. if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
  130. {
  131. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " +
  132. "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
  133. defaultCompileLanguage = "lsl";
  134. }
  135. // Is this language in allow-list?
  136. if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
  137. {
  138. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " +
  139. "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
  140. }
  141. else
  142. {
  143. #if DEBUG
  144. // m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: " +
  145. // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
  146. #endif
  147. // LANGUAGE IS IN ALLOW-LIST
  148. DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
  149. }
  150. // We now have an allow-list, a mapping list, and a default language
  151. }
  152. /// <summary>
  153. /// Delete old script files
  154. /// </summary>
  155. private void DeleteOldFiles()
  156. {
  157. // CREATE FOLDER IF IT DOESNT EXIST
  158. if (!Directory.Exists(ScriptEnginesPath))
  159. {
  160. try
  161. {
  162. Directory.CreateDirectory(ScriptEnginesPath);
  163. }
  164. catch (Exception ex)
  165. {
  166. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
  167. }
  168. }
  169. foreach (string file in Directory.GetFiles(ScriptEnginesPath))
  170. {
  171. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: FILE FOUND: " + file);
  172. if (file.ToLower().StartsWith(FilePrefix + "_compiled_") ||
  173. file.ToLower().StartsWith(FilePrefix + "_source_"))
  174. {
  175. try
  176. {
  177. File.Delete(file);
  178. }
  179. catch (Exception ex)
  180. {
  181. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  182. }
  183. }
  184. }
  185. }
  186. ////private ICodeCompiler icc = codeProvider.CreateCompiler();
  187. //public string CompileFromFile(string LSOFileName)
  188. //{
  189. // switch (Path.GetExtension(LSOFileName).ToLower())
  190. // {
  191. // case ".txt":
  192. // case ".lsl":
  193. // Common.ScriptEngineBase.Common.SendToDebug("Source code is LSL, converting to CS");
  194. // return CompileFromLSLText(File.ReadAllText(LSOFileName));
  195. // case ".cs":
  196. // Common.ScriptEngineBase.Common.SendToDebug("Source code is CS");
  197. // return CompileFromCSText(File.ReadAllText(LSOFileName));
  198. // default:
  199. // throw new Exception("Unknown script type.");
  200. // }
  201. //}
  202. /// <summary>
  203. /// Converts script from LSL to CS and calls CompileFromCSText
  204. /// </summary>
  205. /// <param name="Script">LSL script</param>
  206. /// <returns>Filename to .dll assembly</returns>
  207. public string PerformScriptCompile(string Script)
  208. {
  209. enumCompileType l = DefaultCompileLanguage;
  210. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  211. l = enumCompileType.cs;
  212. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  213. {
  214. l = enumCompileType.vb;
  215. // We need to remove //vb, it won't compile with that
  216. Script = Script.Substring(4, Script.Length - 4);
  217. }
  218. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  219. l = enumCompileType.lsl;
  220. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  221. l = enumCompileType.js;
  222. if (!AllowedCompilers.ContainsKey(l.ToString()))
  223. {
  224. // Not allowed to compile to this language!
  225. string errtext = String.Empty;
  226. errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  227. throw new Exception(errtext);
  228. }
  229. string compileScript = Script;
  230. if (l == enumCompileType.lsl)
  231. {
  232. // Its LSL, convert it to C#
  233. compileScript = LSL_Converter.Convert(Script);
  234. l = enumCompileType.cs;
  235. }
  236. // Insert additional assemblies here
  237. //ADAM: Disabled for the moment until it's working right.
  238. bool enableCommanderLSL = false;
  239. if (enableCommanderLSL == true && l == enumCompileType.cs)
  240. {
  241. foreach (KeyValuePair<string,
  242. ICommander> com
  243. in m_scriptEngine.World.GetCommanders())
  244. {
  245. compileScript = com.Value.GenerateRuntimeAPI() + compileScript;
  246. }
  247. }
  248. // End of insert
  249. switch (l)
  250. {
  251. case enumCompileType.cs:
  252. compileScript = CreateCSCompilerScript(compileScript);
  253. break;
  254. case enumCompileType.vb:
  255. compileScript = CreateVBCompilerScript(compileScript);
  256. break;
  257. case enumCompileType.js:
  258. compileScript = CreateJSCompilerScript(compileScript);
  259. break;
  260. }
  261. m_log.Debug("[ScriptEngine.DotNetEngine]: Preparing to compile the following LSL to C# translated code");
  262. m_log.Debug("");
  263. m_log.Debug(compileScript);
  264. return CompileFromDotNetText(compileScript, l);
  265. }
  266. private static string CreateJSCompilerScript(string compileScript)
  267. {
  268. compileScript = String.Empty +
  269. "import OpenSim.Region.ScriptEngine.Common; import System.Collections.Generic;\r\n" +
  270. "package SecondLife {\r\n" +
  271. "class Script extends OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass { \r\n" +
  272. compileScript +
  273. "} }\r\n";
  274. return compileScript;
  275. }
  276. private static string CreateCSCompilerScript(string compileScript)
  277. {
  278. compileScript = String.Empty +
  279. "using OpenSim.Region.ScriptEngine.Common; using System.Collections.Generic;\r\n" +
  280. String.Empty + "namespace SecondLife { " +
  281. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass { \r\n" +
  282. @"public Script() { } " +
  283. compileScript +
  284. "} }\r\n";
  285. return compileScript;
  286. }
  287. private static string CreateVBCompilerScript(string compileScript)
  288. {
  289. compileScript = String.Empty +
  290. "Imports OpenSim.Region.ScriptEngine.Common: Imports System.Collections.Generic: " +
  291. String.Empty + "NameSpace SecondLife:" +
  292. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass: " +
  293. "\r\nPublic Sub New()\r\nEnd Sub: " +
  294. compileScript +
  295. ":End Class :End Namespace\r\n";
  296. return compileScript;
  297. }
  298. /// <summary>
  299. /// Compile .NET script to .Net assembly (.dll)
  300. /// </summary>
  301. /// <param name="Script">CS script</param>
  302. /// <returns>Filename to .dll assembly</returns>
  303. internal string CompileFromDotNetText(string Script, enumCompileType lang)
  304. {
  305. string ext = "." + lang.ToString();
  306. // Output assembly name
  307. scriptCompileCounter++;
  308. string OutFile =
  309. Path.Combine("ScriptEngines",
  310. FilePrefix + "_compiled_" + instanceID.ToString() + "_" + scriptCompileCounter.ToString() + ".dll");
  311. #if DEBUG
  312. m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Starting compile of \"" + OutFile + "\".");
  313. #endif
  314. try
  315. {
  316. File.Delete(OutFile);
  317. }
  318. catch (Exception e) // NOTLEGIT - Should be just catching FileIOException
  319. {
  320. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  321. throw new Exception("Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  322. }
  323. //string OutFile = Path.Combine("ScriptEngines", "SecondLife.Script.dll");
  324. // DEBUG - write source to disk
  325. if (WriteScriptSourceToDebugFile)
  326. {
  327. string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(OutFile) + ext;
  328. try
  329. {
  330. File.WriteAllText(
  331. Path.Combine("ScriptEngines", srcFileName),
  332. Script);
  333. }
  334. catch (Exception ex) // NOTLEGIT - Should be just catching FileIOException
  335. {
  336. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception while trying to write script source to file \"" + srcFileName + "\": " + ex.ToString());
  337. }
  338. }
  339. // Do actual compile
  340. CompilerParameters parameters = new CompilerParameters();
  341. parameters.IncludeDebugInformation = true;
  342. // Add all available assemblies
  343. // foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
  344. // {
  345. // Console.WriteLine("Adding assembly: " + asm.Location);
  346. // parameters.ReferencedAssemblies.Add(asm.Location);
  347. // }
  348. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  349. string rootPathSE = Path.GetDirectoryName(GetType().Assembly.Location);
  350. //Console.WriteLine("Assembly location: " + rootPath);
  351. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Common.dll"));
  352. parameters.ReferencedAssemblies.Add(Path.Combine(rootPathSE, "OpenSim.Region.ScriptEngine.DotNetEngine.dll"));
  353. //parameters.ReferencedAssemblies.Add("OpenSim.Region.Environment");
  354. parameters.GenerateExecutable = false;
  355. parameters.OutputAssembly = OutFile;
  356. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  357. //parameters.WarningLevel = 1; // Should be 4?
  358. parameters.TreatWarningsAsErrors = false;
  359. CompilerResults results;
  360. switch (lang)
  361. {
  362. case enumCompileType.vb:
  363. results = VBcodeProvider.CompileAssemblyFromSource(parameters, Script);
  364. break;
  365. case enumCompileType.cs:
  366. results = CScodeProvider.CompileAssemblyFromSource(parameters, Script);
  367. break;
  368. case enumCompileType.js:
  369. results = JScodeProvider.CompileAssemblyFromSource(parameters, Script);
  370. break;
  371. default:
  372. throw new Exception("Compiler is not able to recongnize language type \"" + lang.ToString() + "\"");
  373. }
  374. // Check result
  375. // Go through errors
  376. //
  377. // WARNINGS AND ERRORS
  378. //
  379. if (results.Errors.Count > 0)
  380. {
  381. string errtext = String.Empty;
  382. foreach (CompilerError CompErr in results.Errors)
  383. {
  384. errtext += "Line number " + (CompErr.Line - LinesToRemoveOnError) +
  385. ", Error Number: " + CompErr.ErrorNumber +
  386. ", '" + CompErr.ErrorText + "'\r\n";
  387. }
  388. if (!File.Exists(OutFile))
  389. {
  390. throw new Exception(errtext);
  391. }
  392. }
  393. //
  394. // NO ERRORS, BUT NO COMPILED FILE
  395. //
  396. if (!File.Exists(OutFile))
  397. {
  398. string errtext = String.Empty;
  399. errtext += "No compile error. But not able to locate compiled file.";
  400. throw new Exception(errtext);
  401. }
  402. return OutFile;
  403. }
  404. }
  405. }