Compiler.cs 31 KB

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