CILCompiler.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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.IO;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using log4net;
  34. using OpenSim.ScriptEngine.Shared;
  35. using ScriptAssemblies;
  36. namespace OpenSim.ScriptEngine.Components.DotNetEngine.Compilers
  37. {
  38. public abstract class CILCompiler
  39. {
  40. internal static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. private string ScriptEnginesPath = "ScriptEngines";
  42. private string Name { get { return "SECS.DotNetEngine.CILCompiler"; } }
  43. private string m_scriptAssemblyName;
  44. internal string ScriptAssemblyName { get { return m_scriptAssemblyName; } set { m_scriptAssemblyName = value; } }
  45. // Default inherit
  46. protected string ScriptInheritFrom = typeof(ScriptAssemblies.ScriptBase).Name;
  47. private readonly System.Security.Cryptography.MD5CryptoServiceProvider MD5Sum = new System.Security.Cryptography.MD5CryptoServiceProvider();
  48. protected CodeDomProvider CompileProvider;
  49. //private string[] AppDomainAssemblies = new string[] { "OpenSim.Region.ScriptEngine.Shared.dll", "OpenSim.Region.ScriptEngine.Shared.Script.dll", "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll" };
  50. private readonly string[] AppDomainAssemblies = new string[] {
  51. Assembly.GetAssembly(typeof(Int32)).Location,
  52. "OpenSim.ScriptEngine.Shared.dll",
  53. "OpenSim.ScriptEngine.Shared.Script.dll",
  54. Path.Combine("ScriptEngines", "OpenSim.Region.ScriptEngine.Shared.dll")
  55. };
  56. public abstract string PreProcessScript(ref string script);
  57. public CILCompiler()
  58. {
  59. }
  60. private static readonly Regex FileNameFixer = new Regex(@"[^a-zA-Z0-9\.\-]", RegexOptions.Compiled | RegexOptions.Singleline);
  61. public string Compile(ScriptMetaData data, ref string _script)
  62. {
  63. // Add "using", "inherit", default constructor, etc around script.
  64. string script = PreProcessScript(ref _script);
  65. // Get filename based on content
  66. string md5Sum = System.Convert.ToBase64String(
  67. MD5Sum.ComputeHash(
  68. System.Text.Encoding.ASCII.GetBytes(script)
  69. ));
  70. // Unique name for this assembly
  71. ScriptAssemblyName = "SECS_Script_" + FileNameFixer.Replace(md5Sum, "_");
  72. string OutFile = Path.Combine(ScriptEnginesPath, ScriptAssemblyName + ".dll");
  73. // Make sure target dir exist
  74. if (!Directory.Exists(ScriptEnginesPath))
  75. try { Directory.CreateDirectory(ScriptEnginesPath); }
  76. catch { }
  77. // Already exist? No point in recompiling
  78. if (File.Exists(OutFile))
  79. return OutFile;
  80. //
  81. // Dump source code
  82. //
  83. string dumpFile = OutFile + ".txt";
  84. try
  85. {
  86. if (File.Exists(dumpFile))
  87. File.Delete(dumpFile);
  88. File.WriteAllText(dumpFile, script);
  89. }
  90. catch (Exception e)
  91. {
  92. m_log.DebugFormat("[{0}] Exception trying to dump script source code to file \"{1}\": {2}", Name, dumpFile, e.ToString());
  93. }
  94. //
  95. // COMPILE
  96. //
  97. CompilerParameters parameters = new CompilerParameters();
  98. parameters.IncludeDebugInformation = true;
  99. //string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  100. foreach (string file in AppDomainAssemblies)
  101. {
  102. parameters.ReferencedAssemblies.Add(file);
  103. m_log.DebugFormat("[{0}] Adding reference for compile: \"{1}\".", Name, file);
  104. }
  105. //lock (commandProvider)
  106. //{
  107. // foreach (string key in commandProvider.Keys)
  108. // {
  109. // IScriptCommandProvider cp = commandProvider[key];
  110. // string
  111. // file = cp.GetType().Assembly.Location;
  112. // parameters.ReferencedAssemblies.Add(file);
  113. // m_log.DebugFormat("[{0}] Loading command provider assembly \"{1}\" into AppDomain: \"{2}\".", Name,
  114. // key, file);
  115. // }
  116. //}
  117. parameters.GenerateExecutable = false;
  118. parameters.OutputAssembly = OutFile;
  119. parameters.IncludeDebugInformation = true;
  120. //parameters.WarningLevel = 1; // Should be 4?
  121. parameters.TreatWarningsAsErrors = false;
  122. // Do compile
  123. CompilerResults results = CompileProvider.CompileAssemblyFromSource(parameters, script);
  124. //
  125. // WARNINGS AND ERRORS
  126. //
  127. //TODO
  128. int display = 5;
  129. if (results.Errors.Count > 0)
  130. {
  131. string errtext = String.Empty;
  132. foreach (CompilerError CompErr in results.Errors)
  133. {
  134. // Show 5 errors max
  135. //
  136. if (display <= 0)
  137. break;
  138. display--;
  139. string severity = "Error";
  140. if (CompErr.IsWarning)
  141. severity = "Warning";
  142. //TODO: Implement
  143. KeyValuePair<int, int> lslPos = new KeyValuePair<int, int>();
  144. //lslPos = "NOT IMPLEMENTED";// FindErrorPosition(CompErr.Line, CompErr.Column);
  145. string text = CompErr.ErrorText;
  146. // The Second Life viewer's script editor begins
  147. // countingn lines and columns at 0, so we subtract 1.
  148. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  149. lslPos.Key - 1, lslPos.Value - 1,
  150. CompErr.ErrorNumber, text, severity);
  151. }
  152. if (!File.Exists(OutFile))
  153. {
  154. throw new Exception(errtext);
  155. }
  156. }
  157. // TODO: Process errors
  158. return OutFile;
  159. }
  160. }
  161. }