Compiler.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 System.Reflection;
  33. using Microsoft.CSharp;
  34. using Microsoft.VisualBasic;
  35. using Microsoft.JScript;
  36. namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.LSL
  37. {
  38. public class Compiler
  39. {
  40. // * Uses "LSL2Converter" to convert LSL to C# if necessary.
  41. // * Compiles C#-code into an assembly
  42. // * Returns assembly name ready for AppDomain load.
  43. //
  44. // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
  45. //
  46. internal enum enumCompileType
  47. {
  48. lsl = 0,
  49. cs = 1,
  50. vb = 2,
  51. js = 3
  52. }
  53. /// <summary>
  54. /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
  55. /// </summary>
  56. public int LinesToRemoveOnError = 3;
  57. private enumCompileType DefaultCompileLanguage;
  58. private bool WriteScriptSourceToDebugFile;
  59. private bool CompileWithDebugInformation;
  60. private bool CleanUpOldScriptsOnStartup;
  61. private System.Collections.Generic.Dictionary<string, Boolean> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  62. private System.Collections.Generic.Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  63. private string FilePrefix;
  64. private string ScriptEnginesPath = "ScriptEngines";
  65. private static LSL2CSConverter LSL_Converter = new LSL2CSConverter();
  66. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  67. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  68. private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
  69. private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  70. private static UInt64 scriptCompileCounter = 0; // And a counter
  71. public Common.ScriptEngineBase.ScriptEngine m_scriptEngine;
  72. public Compiler(Common.ScriptEngineBase.ScriptEngine scriptEngine)
  73. {
  74. m_scriptEngine = scriptEngine;
  75. ReadConfig();
  76. }
  77. public bool in_startup = true;
  78. public void ReadConfig()
  79. {
  80. // Get some config
  81. WriteScriptSourceToDebugFile = m_scriptEngine.ScriptConfigSource.GetBoolean("WriteScriptSourceToDebugFile", true);
  82. CompileWithDebugInformation = m_scriptEngine.ScriptConfigSource.GetBoolean("CompileWithDebugInformation", true);
  83. CleanUpOldScriptsOnStartup = m_scriptEngine.ScriptConfigSource.GetBoolean("CleanUpOldScriptsOnStartup", 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. foreach (string file in Directory.GetFiles(ScriptEnginesPath))
  168. {
  169. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: FILE FOUND: " + file);
  170. if (file.ToLower().StartsWith(FilePrefix + "_compiled_") ||
  171. file.ToLower().StartsWith(FilePrefix + "_source_"))
  172. {
  173. try
  174. {
  175. File.Delete(file);
  176. }
  177. catch (Exception ex)
  178. {
  179. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  180. }
  181. }
  182. }
  183. }
  184. ////private ICodeCompiler icc = codeProvider.CreateCompiler();
  185. //public string CompileFromFile(string LSOFileName)
  186. //{
  187. // switch (Path.GetExtension(LSOFileName).ToLower())
  188. // {
  189. // case ".txt":
  190. // case ".lsl":
  191. // Common.ScriptEngineBase.Common.SendToDebug("Source code is LSL, converting to CS");
  192. // return CompileFromLSLText(File.ReadAllText(LSOFileName));
  193. // case ".cs":
  194. // Common.ScriptEngineBase.Common.SendToDebug("Source code is CS");
  195. // return CompileFromCSText(File.ReadAllText(LSOFileName));
  196. // default:
  197. // throw new Exception("Unknown script type.");
  198. // }
  199. //}
  200. /// <summary>
  201. /// Converts script from LSL to CS and calls CompileFromCSText
  202. /// </summary>
  203. /// <param name="Script">LSL script</param>
  204. /// <returns>Filename to .dll assembly</returns>
  205. public string PerformScriptCompile(string Script)
  206. {
  207. enumCompileType l = DefaultCompileLanguage;
  208. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  209. l = enumCompileType.cs;
  210. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  211. {
  212. l = enumCompileType.vb;
  213. // We need to remove //vb, it won't compile with that
  214. Script = Script.Substring(4, Script.Length - 4);
  215. }
  216. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  217. l = enumCompileType.lsl;
  218. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  219. l = enumCompileType.js;
  220. if (!AllowedCompilers.ContainsKey(l.ToString()))
  221. {
  222. // Not allowed to compile to this language!
  223. string errtext = String.Empty;
  224. errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  225. throw new Exception(errtext);
  226. }
  227. string compileScript = Script;
  228. if (l == enumCompileType.lsl)
  229. {
  230. // Its LSL, convert it to C#
  231. compileScript = LSL_Converter.Convert(Script);
  232. l = enumCompileType.cs;
  233. }
  234. // Insert additional assemblies here
  235. //ADAM: Disabled for the moment until it's working right.
  236. bool enableCommanderLSL = false;
  237. if (enableCommanderLSL == true && l == enumCompileType.cs)
  238. {
  239. foreach (KeyValuePair<string,
  240. OpenSim.Region.Environment.Interfaces.ICommander> com
  241. in m_scriptEngine.World.GetCommanders())
  242. {
  243. compileScript = com.Value.GenerateRuntimeAPI() + compileScript;
  244. }
  245. }
  246. // End of insert
  247. switch (l)
  248. {
  249. case enumCompileType.cs:
  250. compileScript = CreateCSCompilerScript(compileScript);
  251. break;
  252. case enumCompileType.vb:
  253. compileScript = CreateVBCompilerScript(compileScript);
  254. break;
  255. case enumCompileType.js:
  256. compileScript = CreateJSCompilerScript(compileScript);
  257. break;
  258. }
  259. Console.WriteLine("\n\n\n");
  260. Console.WriteLine(compileScript);
  261. Console.WriteLine("\n\n\n");
  262. return CompileFromDotNetText(compileScript, l);
  263. }
  264. private static string CreateJSCompilerScript(string compileScript)
  265. {
  266. compileScript = String.Empty +
  267. "import OpenSim.Region.ScriptEngine.Common; import System.Collections.Generic;\r\n" +
  268. "package SecondLife {\r\n" +
  269. "class Script extends OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass { \r\n" +
  270. compileScript +
  271. "} }\r\n";
  272. return compileScript;
  273. }
  274. private static string CreateCSCompilerScript(string compileScript)
  275. {
  276. compileScript = String.Empty +
  277. "using OpenSim.Region.ScriptEngine.Common; using System.Collections.Generic;\r\n" +
  278. String.Empty + "namespace SecondLife { " +
  279. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass { \r\n" +
  280. @"public Script() { } " +
  281. compileScript +
  282. "} }\r\n";
  283. return compileScript;
  284. }
  285. private static string CreateVBCompilerScript(string compileScript)
  286. {
  287. compileScript = String.Empty +
  288. "Imports OpenSim.Region.ScriptEngine.Common: Imports System.Collections.Generic: " +
  289. String.Empty + "NameSpace SecondLife:" +
  290. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Common.BuiltIn_Commands_BaseClass: " +
  291. "\r\nPublic Sub New()\r\nEnd Sub: " +
  292. compileScript +
  293. ":End Class :End Namespace\r\n";
  294. return compileScript;
  295. }
  296. /// <summary>
  297. /// Compile .NET script to .Net assembly (.dll)
  298. /// </summary>
  299. /// <param name="Script">CS script</param>
  300. /// <returns>Filename to .dll assembly</returns>
  301. internal string CompileFromDotNetText(string Script, enumCompileType lang)
  302. {
  303. string ext = "." + lang.ToString();
  304. // Output assembly name
  305. scriptCompileCounter++;
  306. string OutFile =
  307. Path.Combine("ScriptEngines",
  308. FilePrefix + "_compiled_" + instanceID.ToString() + "_" + scriptCompileCounter.ToString() + ".dll");
  309. #if DEBUG
  310. m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Starting compile of \"" + OutFile + "\".");
  311. #endif
  312. try
  313. {
  314. File.Delete(OutFile);
  315. }
  316. catch (Exception e) // NOTLEGIT - Should be just catching FileIOException
  317. {
  318. //m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  319. throw new Exception("Unable to delete old existring script-file before writing new. Compile aborted: " + e.ToString());
  320. }
  321. //string OutFile = Path.Combine("ScriptEngines", "SecondLife.Script.dll");
  322. // DEBUG - write source to disk
  323. if (WriteScriptSourceToDebugFile)
  324. {
  325. string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(OutFile) + ext;
  326. try
  327. {
  328. File.WriteAllText(
  329. Path.Combine("ScriptEngines", srcFileName),
  330. Script);
  331. }
  332. catch (Exception ex) // NOTLEGIT - Should be just catching FileIOException
  333. {
  334. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception while trying to write script source to file \"" + srcFileName + "\": " + ex.ToString());
  335. }
  336. }
  337. // Do actual compile
  338. CompilerParameters parameters = new CompilerParameters();
  339. parameters.IncludeDebugInformation = true;
  340. // Add all available assemblies
  341. // foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
  342. // {
  343. // Console.WriteLine("Adding assembly: " + asm.Location);
  344. // parameters.ReferencedAssemblies.Add(asm.Location);
  345. // }
  346. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  347. string rootPathSE = Path.GetDirectoryName(GetType().Assembly.Location);
  348. //Console.WriteLine("Assembly location: " + rootPath);
  349. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Common.dll"));
  350. parameters.ReferencedAssemblies.Add(Path.Combine(rootPathSE, "OpenSim.Region.ScriptEngine.DotNetEngine.dll"));
  351. //parameters.ReferencedAssemblies.Add("OpenSim.Region.Environment");
  352. parameters.GenerateExecutable = false;
  353. parameters.OutputAssembly = OutFile;
  354. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  355. //parameters.WarningLevel = 1; // Should be 4?
  356. parameters.TreatWarningsAsErrors = false;
  357. CompilerResults results;
  358. switch (lang)
  359. {
  360. case enumCompileType.vb:
  361. results = VBcodeProvider.CompileAssemblyFromSource(parameters, Script);
  362. break;
  363. case enumCompileType.cs:
  364. results = CScodeProvider.CompileAssemblyFromSource(parameters, Script);
  365. break;
  366. case enumCompileType.js:
  367. results = JScodeProvider.CompileAssemblyFromSource(parameters, Script);
  368. break;
  369. default:
  370. throw new Exception("Compiler is not able to recongnize language type \"" + lang.ToString() + "\"");
  371. }
  372. // Check result
  373. // Go through errors
  374. //
  375. // WARNINGS AND ERRORS
  376. //
  377. if (results.Errors.Count > 0)
  378. {
  379. string errtext = String.Empty;
  380. foreach (CompilerError CompErr in results.Errors)
  381. {
  382. errtext += "Line number " + (CompErr.Line - LinesToRemoveOnError) +
  383. ", Error Number: " + CompErr.ErrorNumber +
  384. ", '" + CompErr.ErrorText + "'\r\n";
  385. }
  386. if (!File.Exists(OutFile))
  387. {
  388. throw new Exception(errtext);
  389. }
  390. }
  391. //
  392. // NO ERRORS, BUT NO COMPILED FILE
  393. //
  394. if (!File.Exists(OutFile))
  395. {
  396. string errtext = String.Empty;
  397. errtext += "No compile error. But not able to locate compiled file.";
  398. throw new Exception(errtext);
  399. }
  400. return OutFile;
  401. }
  402. }
  403. }