Compiler.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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.Globalization;
  31. using System.Reflection;
  32. using System.IO;
  33. using System.Text;
  34. using Microsoft.CSharp;
  35. //using Microsoft.JScript;
  36. using Microsoft.VisualBasic;
  37. using log4net;
  38. using OpenSim.Region.Framework.Interfaces;
  39. using OpenSim.Region.ScriptEngine.Interfaces;
  40. using OpenMetaverse;
  41. namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
  42. {
  43. public class Compiler : ICompiler
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. // * Uses "LSL2Converter" to convert LSL to C# if necessary.
  47. // * Compiles C#-code into an assembly
  48. // * Returns assembly name ready for AppDomain load.
  49. //
  50. // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
  51. //
  52. internal enum enumCompileType
  53. {
  54. lsl = 0,
  55. cs = 1,
  56. vb = 2,
  57. js = 3,
  58. yp = 4
  59. }
  60. /// <summary>
  61. /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
  62. /// </summary>
  63. public int LinesToRemoveOnError = 3;
  64. private enumCompileType DefaultCompileLanguage;
  65. private bool WriteScriptSourceToDebugFile;
  66. private bool CompileWithDebugInformation;
  67. private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  68. private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  69. private string FilePrefix;
  70. private string ScriptEnginesPath = null;
  71. // mapping between LSL and C# line/column numbers
  72. private ICodeConverter LSL_Converter;
  73. private List<string> m_warnings = new List<string>();
  74. // private object m_syncy = new object();
  75. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  76. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  77. // private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
  78. private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp
  79. private static YP2CSConverter YP_Converter = new YP2CSConverter();
  80. // private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  81. private static UInt64 scriptCompileCounter = 0; // And a counter
  82. public IScriptEngine m_scriptEngine;
  83. private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
  84. new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
  85. public Compiler(IScriptEngine scriptEngine)
  86. {
  87. m_scriptEngine = scriptEngine;;
  88. ScriptEnginesPath = scriptEngine.ScriptEnginePath;
  89. ReadConfig();
  90. }
  91. public bool in_startup = true;
  92. public void ReadConfig()
  93. {
  94. // Get some config
  95. WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
  96. CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
  97. bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
  98. // Get file prefix from scriptengine name and make it file system safe:
  99. FilePrefix = "CommonCompiler";
  100. foreach (char c in Path.GetInvalidFileNameChars())
  101. {
  102. FilePrefix = FilePrefix.Replace(c, '_');
  103. }
  104. if (in_startup)
  105. {
  106. in_startup = false;
  107. CreateScriptsDirectory();
  108. // First time we start? Delete old files
  109. if (DeleteScriptsOnStartup)
  110. DeleteOldFiles();
  111. }
  112. // Map name and enum type of our supported languages
  113. LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
  114. LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
  115. LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
  116. LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
  117. LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp);
  118. // Allowed compilers
  119. string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
  120. AllowedCompilers.Clear();
  121. #if DEBUG
  122. m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
  123. #endif
  124. foreach (string strl in allowComp.Split(','))
  125. {
  126. string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
  127. if (!LanguageMapping.ContainsKey(strlan))
  128. {
  129. m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  130. }
  131. else
  132. {
  133. #if DEBUG
  134. //m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
  135. #endif
  136. }
  137. AllowedCompilers.Add(strlan, true);
  138. }
  139. if (AllowedCompilers.Count == 0)
  140. m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
  141. // Default language
  142. string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
  143. // Is this language recognized at all?
  144. if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
  145. {
  146. m_log.Error("[Compiler]: " +
  147. "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
  148. defaultCompileLanguage = "lsl";
  149. }
  150. // Is this language in allow-list?
  151. if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
  152. {
  153. m_log.Error("[Compiler]: " +
  154. "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
  155. }
  156. else
  157. {
  158. #if DEBUG
  159. // m_log.Debug("[Compiler]: " +
  160. // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
  161. #endif
  162. // LANGUAGE IS IN ALLOW-LIST
  163. DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
  164. }
  165. // We now have an allow-list, a mapping list, and a default language
  166. }
  167. /// <summary>
  168. /// Create the directory where compiled scripts are stored.
  169. /// </summary>
  170. private void CreateScriptsDirectory()
  171. {
  172. if (!Directory.Exists(ScriptEnginesPath))
  173. {
  174. try
  175. {
  176. Directory.CreateDirectory(ScriptEnginesPath);
  177. }
  178. catch (Exception ex)
  179. {
  180. m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
  181. }
  182. }
  183. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  184. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  185. {
  186. try
  187. {
  188. Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
  189. m_scriptEngine.World.RegionInfo.RegionID.ToString()));
  190. }
  191. catch (Exception ex)
  192. {
  193. m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
  194. m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString());
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// Delete old script files
  200. /// </summary>
  201. private void DeleteOldFiles()
  202. {
  203. foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
  204. m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*"))
  205. {
  206. try
  207. {
  208. File.Delete(file);
  209. }
  210. catch (Exception ex)
  211. {
  212. m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  213. }
  214. }
  215. foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
  216. m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
  217. {
  218. try
  219. {
  220. File.Delete(file);
  221. }
  222. catch (Exception ex)
  223. {
  224. m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
  225. }
  226. }
  227. }
  228. ////private ICodeCompiler icc = codeProvider.CreateCompiler();
  229. //public string CompileFromFile(string LSOFileName)
  230. //{
  231. // switch (Path.GetExtension(LSOFileName).ToLower())
  232. // {
  233. // case ".txt":
  234. // case ".lsl":
  235. // Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
  236. // return CompileFromLSLText(File.ReadAllText(LSOFileName));
  237. // case ".cs":
  238. // Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
  239. // return CompileFromCSText(File.ReadAllText(LSOFileName));
  240. // default:
  241. // throw new Exception("Unknown script type.");
  242. // }
  243. //}
  244. public string GetCompilerOutput(string assetID)
  245. {
  246. return Path.Combine(ScriptEnginesPath, Path.Combine(
  247. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  248. FilePrefix + "_compiled_" + assetID + ".dll"));
  249. }
  250. public string GetCompilerOutput(UUID assetID)
  251. {
  252. return GetCompilerOutput(assetID.ToString());
  253. }
  254. /// <summary>
  255. /// Converts script from LSL to CS and calls CompileFromCSText
  256. /// </summary>
  257. /// <param name="Script">LSL script</param>
  258. /// <returns>Filename to .dll assembly</returns>
  259. public void PerformScriptCompile(string Script, string asset, UUID ownerUUID,
  260. out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
  261. {
  262. // m_log.DebugFormat("[Compiler]: Compiling script\n{0}", Script);
  263. linemap = null;
  264. m_warnings.Clear();
  265. assembly = GetCompilerOutput(asset);
  266. if (!Directory.Exists(ScriptEnginesPath))
  267. {
  268. try
  269. {
  270. Directory.CreateDirectory(ScriptEnginesPath);
  271. }
  272. catch (Exception)
  273. {
  274. }
  275. }
  276. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  277. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  278. {
  279. try
  280. {
  281. Directory.CreateDirectory(ScriptEnginesPath);
  282. }
  283. catch (Exception)
  284. {
  285. }
  286. }
  287. // Don't recompile if we already have it
  288. // Performing 3 file exists tests for every script can still be slow
  289. if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
  290. {
  291. // If we have already read this linemap file, then it will be in our dictionary.
  292. // Don't build another copy of the dictionary (saves memory) and certainly
  293. // don't keep reading the same file from disk multiple times.
  294. if (!m_lineMaps.ContainsKey(assembly))
  295. m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
  296. linemap = m_lineMaps[assembly];
  297. return;
  298. }
  299. if (Script == String.Empty)
  300. {
  301. throw new Exception("Cannot find script assembly and no script text present");
  302. }
  303. enumCompileType language = DefaultCompileLanguage;
  304. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  305. language = enumCompileType.cs;
  306. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  307. {
  308. language = enumCompileType.vb;
  309. // We need to remove //vb, it won't compile with that
  310. Script = Script.Substring(4, Script.Length - 4);
  311. }
  312. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  313. language = enumCompileType.lsl;
  314. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  315. language = enumCompileType.js;
  316. if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
  317. language = enumCompileType.yp;
  318. // m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
  319. if (!AllowedCompilers.ContainsKey(language.ToString()))
  320. {
  321. // Not allowed to compile to this language!
  322. string errtext = String.Empty;
  323. errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  324. throw new Exception(errtext);
  325. }
  326. if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
  327. {
  328. // Not allowed to compile to this language!
  329. string errtext = String.Empty;
  330. errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
  331. throw new Exception(errtext);
  332. }
  333. string compileScript = Script;
  334. if (language == enumCompileType.lsl)
  335. {
  336. // Its LSL, convert it to C#
  337. LSL_Converter = (ICodeConverter)new CSCodeGenerator();
  338. compileScript = LSL_Converter.Convert(Script);
  339. // copy converter warnings into our warnings.
  340. foreach (string warning in LSL_Converter.GetWarnings())
  341. {
  342. AddWarning(warning);
  343. }
  344. linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
  345. // Write the linemap to a file and save it in our dictionary for next time.
  346. m_lineMaps[assembly] = linemap;
  347. WriteMapFile(assembly + ".map", linemap);
  348. }
  349. if (language == enumCompileType.yp)
  350. {
  351. // Its YP, convert it to C#
  352. compileScript = YP_Converter.Convert(Script);
  353. }
  354. switch (language)
  355. {
  356. case enumCompileType.cs:
  357. case enumCompileType.lsl:
  358. compileScript = CreateCSCompilerScript(compileScript);
  359. break;
  360. case enumCompileType.vb:
  361. compileScript = CreateVBCompilerScript(compileScript);
  362. break;
  363. // case enumCompileType.js:
  364. // compileScript = CreateJSCompilerScript(compileScript);
  365. // break;
  366. case enumCompileType.yp:
  367. compileScript = CreateYPCompilerScript(compileScript);
  368. break;
  369. }
  370. assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
  371. }
  372. public string[] GetWarnings()
  373. {
  374. return m_warnings.ToArray();
  375. }
  376. private void AddWarning(string warning)
  377. {
  378. if (!m_warnings.Contains(warning))
  379. {
  380. m_warnings.Add(warning);
  381. }
  382. }
  383. // private static string CreateJSCompilerScript(string compileScript)
  384. // {
  385. // compileScript = String.Empty +
  386. // "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
  387. // "package SecondLife {\r\n" +
  388. // "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  389. // compileScript +
  390. // "} }\r\n";
  391. // return compileScript;
  392. // }
  393. private static string CreateCSCompilerScript(string compileScript)
  394. {
  395. compileScript = String.Empty +
  396. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  397. String.Empty + "namespace SecondLife { " +
  398. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  399. @"public Script() { } " +
  400. compileScript +
  401. "} }\r\n";
  402. return compileScript;
  403. }
  404. private static string CreateYPCompilerScript(string compileScript)
  405. {
  406. compileScript = String.Empty +
  407. "using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " +
  408. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  409. String.Empty + "namespace SecondLife { " +
  410. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  411. //@"public Script() { } " +
  412. @"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " +
  413. @"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " +
  414. compileScript +
  415. "} }\r\n";
  416. return compileScript;
  417. }
  418. private static string CreateVBCompilerScript(string compileScript)
  419. {
  420. compileScript = String.Empty +
  421. "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
  422. String.Empty + "NameSpace SecondLife:" +
  423. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " +
  424. "\r\nPublic Sub New()\r\nEnd Sub: " +
  425. compileScript +
  426. ":End Class :End Namespace\r\n";
  427. return compileScript;
  428. }
  429. /// <summary>
  430. /// Compile .NET script to .Net assembly (.dll)
  431. /// </summary>
  432. /// <param name="Script">CS script</param>
  433. /// <returns>Filename to .dll assembly</returns>
  434. internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
  435. {
  436. // m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
  437. string ext = "." + lang.ToString();
  438. // Output assembly name
  439. scriptCompileCounter++;
  440. try
  441. {
  442. File.Delete(assembly);
  443. }
  444. catch (Exception e) // NOTLEGIT - Should be just FileIOException
  445. {
  446. throw new Exception("Unable to delete old existing " +
  447. "script-file before writing new. Compile aborted: " +
  448. e.ToString());
  449. }
  450. // DEBUG - write source to disk
  451. if (WriteScriptSourceToDebugFile)
  452. {
  453. string srcFileName = FilePrefix + "_source_" +
  454. Path.GetFileNameWithoutExtension(assembly) + ext;
  455. try
  456. {
  457. File.WriteAllText(Path.Combine(Path.Combine(
  458. ScriptEnginesPath,
  459. m_scriptEngine.World.RegionInfo.RegionID.ToString()),
  460. srcFileName), Script);
  461. }
  462. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  463. {
  464. m_log.Error("[Compiler]: Exception while " +
  465. "trying to write script source to file \"" +
  466. srcFileName + "\": " + ex.ToString());
  467. }
  468. }
  469. // Do actual compile
  470. CompilerParameters parameters = new CompilerParameters();
  471. parameters.IncludeDebugInformation = true;
  472. string rootPath = AppDomain.CurrentDomain.BaseDirectory;
  473. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  474. "OpenSim.Region.ScriptEngine.Shared.dll"));
  475. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  476. "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
  477. if (lang == enumCompileType.yp)
  478. {
  479. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  480. "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
  481. }
  482. parameters.GenerateExecutable = false;
  483. parameters.OutputAssembly = assembly;
  484. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  485. //parameters.WarningLevel = 1; // Should be 4?
  486. parameters.TreatWarningsAsErrors = false;
  487. CompilerResults results;
  488. switch (lang)
  489. {
  490. case enumCompileType.vb:
  491. results = VBcodeProvider.CompileAssemblyFromSource(
  492. parameters, Script);
  493. break;
  494. case enumCompileType.cs:
  495. case enumCompileType.lsl:
  496. bool complete = false;
  497. bool retried = false;
  498. do
  499. {
  500. lock (CScodeProvider)
  501. {
  502. results = CScodeProvider.CompileAssemblyFromSource(
  503. parameters, Script);
  504. }
  505. // Deal with an occasional segv in the compiler.
  506. // Rarely, if ever, occurs twice in succession.
  507. // Line # == 0 and no file name are indications that
  508. // this is a native stack trace rather than a normal
  509. // error log.
  510. if (results.Errors.Count > 0)
  511. {
  512. if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
  513. results.Errors[0].Line == 0)
  514. {
  515. // System.Console.WriteLine("retrying failed compilation");
  516. retried = true;
  517. }
  518. else
  519. {
  520. complete = true;
  521. }
  522. }
  523. else
  524. {
  525. complete = true;
  526. }
  527. } while (!complete);
  528. break;
  529. // case enumCompileType.js:
  530. // results = JScodeProvider.CompileAssemblyFromSource(
  531. // parameters, Script);
  532. // break;
  533. case enumCompileType.yp:
  534. results = YPcodeProvider.CompileAssemblyFromSource(
  535. parameters, Script);
  536. break;
  537. default:
  538. throw new Exception("Compiler is not able to recongnize " +
  539. "language type \"" + lang.ToString() + "\"");
  540. }
  541. // Check result
  542. // Go through errors
  543. //
  544. // WARNINGS AND ERRORS
  545. //
  546. bool hadErrors = false;
  547. string errtext = String.Empty;
  548. if (results.Errors.Count > 0)
  549. {
  550. foreach (CompilerError CompErr in results.Errors)
  551. {
  552. string severity = CompErr.IsWarning ? "Warning" : "Error";
  553. KeyValuePair<int, int> lslPos;
  554. // Show 5 errors max, but check entire list for errors
  555. if (severity == "Error")
  556. {
  557. lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
  558. string text = CompErr.ErrorText;
  559. // Use LSL type names
  560. if (lang == enumCompileType.lsl)
  561. text = ReplaceTypes(CompErr.ErrorText);
  562. // The Second Life viewer's script editor begins
  563. // countingn lines and columns at 0, so we subtract 1.
  564. errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
  565. lslPos.Key - 1, lslPos.Value - 1,
  566. CompErr.ErrorNumber, text, severity);
  567. hadErrors = true;
  568. }
  569. }
  570. }
  571. if (hadErrors)
  572. {
  573. throw new Exception(errtext);
  574. }
  575. // On today's highly asynchronous systems, the result of
  576. // the compile may not be immediately apparent. Wait a
  577. // reasonable amount of time before giving up on it.
  578. if (!File.Exists(assembly))
  579. {
  580. for (int i = 0; i < 20 && !File.Exists(assembly); i++)
  581. {
  582. System.Threading.Thread.Sleep(250);
  583. }
  584. // One final chance...
  585. if (!File.Exists(assembly))
  586. {
  587. errtext = String.Empty;
  588. errtext += "No compile error. But not able to locate compiled file.";
  589. throw new Exception(errtext);
  590. }
  591. }
  592. // m_log.DebugFormat("[Compiler] Compiled new assembly "+
  593. // "for {0}", asset);
  594. // Because windows likes to perform exclusive locks, we simply
  595. // write out a textual representation of the file here
  596. //
  597. // Read the binary file into a buffer
  598. //
  599. FileInfo fi = new FileInfo(assembly);
  600. if (fi == null)
  601. {
  602. errtext = String.Empty;
  603. errtext += "No compile error. But not able to stat file.";
  604. throw new Exception(errtext);
  605. }
  606. Byte[] data = new Byte[fi.Length];
  607. try
  608. {
  609. FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
  610. fs.Read(data, 0, data.Length);
  611. fs.Close();
  612. }
  613. catch (Exception)
  614. {
  615. errtext = String.Empty;
  616. errtext += "No compile error. But not able to open file.";
  617. throw new Exception(errtext);
  618. }
  619. // Convert to base64
  620. //
  621. string filetext = System.Convert.ToBase64String(data);
  622. Byte[] buf = Encoding.ASCII.GetBytes(filetext);
  623. FileStream sfs = File.Create(assembly + ".text");
  624. sfs.Write(buf, 0, buf.Length);
  625. sfs.Close();
  626. return assembly;
  627. }
  628. private class kvpSorter : IComparer<KeyValuePair<int, int>>
  629. {
  630. public int Compare(KeyValuePair<int, int> a,
  631. KeyValuePair<int, int> b)
  632. {
  633. return a.Key.CompareTo(b.Key);
  634. }
  635. }
  636. public static KeyValuePair<int, int> FindErrorPosition(int line,
  637. int col, Dictionary<KeyValuePair<int, int>,
  638. KeyValuePair<int, int>> positionMap)
  639. {
  640. if (positionMap == null || positionMap.Count == 0)
  641. return new KeyValuePair<int, int>(line, col);
  642. KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
  643. if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
  644. out ret))
  645. return ret;
  646. List<KeyValuePair<int, int>> sorted =
  647. new List<KeyValuePair<int, int>>(positionMap.Keys);
  648. sorted.Sort(new kvpSorter());
  649. int l = 1;
  650. int c = 1;
  651. foreach (KeyValuePair<int, int> cspos in sorted)
  652. {
  653. if (cspos.Key >= line)
  654. {
  655. if (cspos.Key > line)
  656. return new KeyValuePair<int, int>(l, c);
  657. if (cspos.Value > col)
  658. return new KeyValuePair<int, int>(l, c);
  659. c = cspos.Value;
  660. if (c == 0)
  661. c++;
  662. }
  663. else
  664. {
  665. l = cspos.Key;
  666. }
  667. }
  668. return new KeyValuePair<int, int>(l, c);
  669. }
  670. string ReplaceTypes(string message)
  671. {
  672. message = message.Replace(
  673. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
  674. "string");
  675. message = message.Replace(
  676. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
  677. "integer");
  678. message = message.Replace(
  679. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
  680. "float");
  681. message = message.Replace(
  682. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
  683. "list");
  684. return message;
  685. }
  686. private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
  687. {
  688. string mapstring = String.Empty;
  689. foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
  690. {
  691. KeyValuePair<int, int> k = kvp.Key;
  692. KeyValuePair<int, int> v = kvp.Value;
  693. mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
  694. }
  695. Byte[] mapbytes = Encoding.ASCII.GetBytes(mapstring);
  696. FileStream mfs = File.Create(filename);
  697. mfs.Write(mapbytes, 0, mapbytes.Length);
  698. mfs.Close();
  699. }
  700. private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
  701. {
  702. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  703. try
  704. {
  705. StreamReader r = File.OpenText(filename);
  706. linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
  707. string line;
  708. while ((line = r.ReadLine()) != null)
  709. {
  710. String[] parts = line.Split(new Char[] { ',' });
  711. int kk = System.Convert.ToInt32(parts[0]);
  712. int kv = System.Convert.ToInt32(parts[1]);
  713. int vk = System.Convert.ToInt32(parts[2]);
  714. int vv = System.Convert.ToInt32(parts[3]);
  715. KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
  716. KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
  717. linemap[k] = v;
  718. }
  719. }
  720. catch
  721. {
  722. linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
  723. }
  724. return linemap;
  725. }
  726. }
  727. }