MRMModule.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 OpenSimulator 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;
  33. using log4net;
  34. using Microsoft.CSharp;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
  40. {
  41. public class MRMModule : IRegionModule
  42. {
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private Scene m_scene;
  45. private readonly Dictionary<UUID,MRMBase> m_scripts = new Dictionary<UUID, MRMBase>();
  46. private static readonly CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  47. public void Initialise(Scene scene, IConfigSource source)
  48. {
  49. if (source.Configs["MRM"] != null)
  50. {
  51. if (source.Configs["MRM"].GetBoolean("Enabled", false))
  52. {
  53. m_log.Info("[MRM] Enabling MRM Module");
  54. m_scene = scene;
  55. scene.EventManager.OnRezScript += EventManager_OnRezScript;
  56. }
  57. else
  58. {
  59. m_log.Info("[MRM] Disabled MRM Module (Express)");
  60. }
  61. }
  62. else
  63. {
  64. m_log.Info("[MRM] Disabled MRM Module (Omission)");
  65. }
  66. }
  67. void EventManager_OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  68. {
  69. if (script.StartsWith("//MiniMod:C#"))
  70. {
  71. m_log.Info("[MRM] Found C# MRM");
  72. IWorld m_world = new World(m_scene);
  73. IHost m_host = new Host(new SOPObject(m_scene, localID));
  74. MRMBase mmb = (MRMBase) AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(
  75. CompileFromDotNetText(script, itemID.ToString()),
  76. "OpenSim.MiniModule");
  77. m_log.Info("[MRM] Created MRM Instance");
  78. mmb.InitMiniModule(m_world, m_host);
  79. m_scripts[itemID] = mmb;
  80. m_log.Info("[MRM] Starting MRM");
  81. mmb.Start();
  82. }
  83. }
  84. public void PostInitialise()
  85. {
  86. }
  87. public void Close()
  88. {
  89. foreach (KeyValuePair<UUID, MRMBase> pair in m_scripts)
  90. {
  91. pair.Value.Stop();
  92. }
  93. }
  94. public string Name
  95. {
  96. get { return "MiniRegionModule"; }
  97. }
  98. public bool IsSharedModule
  99. {
  100. get { return false; }
  101. }
  102. /// <summary>
  103. /// Stolen from ScriptEngine Common
  104. /// </summary>
  105. /// <param name="Script"></param>
  106. /// <param name="uuid">Unique ID for this module</param>
  107. /// <returns></returns>
  108. internal string CompileFromDotNetText(string Script, string uuid)
  109. {
  110. const string ext = ".cs";
  111. const string FilePrefix = "MiniModule";
  112. // Output assembly name
  113. string OutFile = Path.Combine("MiniModules", Path.Combine(
  114. m_scene.RegionInfo.RegionID.ToString(),
  115. FilePrefix + "_compiled_" + uuid + ".dll"));
  116. // Create Directories for Assemblies
  117. if (!Directory.Exists("MiniModules"))
  118. Directory.CreateDirectory("MiniModules");
  119. string tmp = Path.Combine("MiniModules", m_scene.RegionInfo.RegionID.ToString());
  120. if (!Directory.Exists(tmp))
  121. Directory.CreateDirectory(tmp);
  122. try
  123. {
  124. File.Delete(OutFile);
  125. }
  126. catch (IOException e)
  127. {
  128. throw new Exception("Unable to delete old existing " +
  129. "script-file before writing new. Compile aborted: " +
  130. e);
  131. }
  132. // DEBUG - write source to disk
  133. string srcFileName = FilePrefix + "_source_" +
  134. Path.GetFileNameWithoutExtension(OutFile) + ext;
  135. try
  136. {
  137. File.WriteAllText(Path.Combine(Path.Combine(
  138. "MiniModules",
  139. m_scene.RegionInfo.RegionID.ToString()),
  140. srcFileName), Script);
  141. }
  142. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  143. {
  144. m_log.Error("[Compiler]: Exception while " +
  145. "trying to write script source to file \"" +
  146. srcFileName + "\": " + ex.ToString());
  147. }
  148. // Do actual compile
  149. CompilerParameters parameters = new CompilerParameters();
  150. parameters.IncludeDebugInformation = true;
  151. string rootPath =
  152. Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  153. // TODO: Add Libraries
  154. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  155. "OpenSim.Region.OptionalModules.dll"));
  156. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  157. "log4net.dll"));
  158. parameters.GenerateExecutable = false;
  159. parameters.OutputAssembly = OutFile;
  160. parameters.IncludeDebugInformation = true;
  161. parameters.TreatWarningsAsErrors = false;
  162. CompilerResults results = CScodeProvider.CompileAssemblyFromSource(
  163. parameters, Script);
  164. int display = 5;
  165. if (results.Errors.Count > 0)
  166. {
  167. string errtext = String.Empty;
  168. foreach (CompilerError CompErr in results.Errors)
  169. {
  170. // Show 5 errors max
  171. //
  172. if (display <= 0)
  173. break;
  174. display--;
  175. string severity = "Error";
  176. if (CompErr.IsWarning)
  177. {
  178. severity = "Warning";
  179. }
  180. string text = CompErr.ErrorText;
  181. // The Second Life viewer's script editor begins
  182. // countingn lines and columns at 0, so we subtract 1.
  183. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  184. CompErr.Line - 1, CompErr.Column - 1,
  185. CompErr.ErrorNumber, text, severity);
  186. }
  187. if (!File.Exists(OutFile))
  188. {
  189. throw new Exception(errtext);
  190. }
  191. }
  192. if (!File.Exists(OutFile))
  193. {
  194. string errtext = String.Empty;
  195. errtext += "No compile error. But not able to locate compiled file.";
  196. throw new Exception(errtext);
  197. }
  198. FileInfo fi = new FileInfo(OutFile);
  199. Byte[] data = new Byte[fi.Length];
  200. try
  201. {
  202. FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
  203. fs.Read(data, 0, data.Length);
  204. fs.Close();
  205. }
  206. catch (IOException)
  207. {
  208. string errtext = String.Empty;
  209. errtext += "No compile error. But not able to open file.";
  210. throw new Exception(errtext);
  211. }
  212. // Convert to base64
  213. //
  214. string filetext = Convert.ToBase64String(data);
  215. ASCIIEncoding enc = new ASCIIEncoding();
  216. Byte[] buf = enc.GetBytes(filetext);
  217. FileStream sfs = File.Create(OutFile + ".cil.b64");
  218. sfs.Write(buf, 0, buf.Length);
  219. sfs.Close();
  220. return OutFile;
  221. }
  222. }
  223. }