Compiler.cs 33 KB

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