Compiler.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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 object GetCompilerOutput(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 object 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. bool complete = false;
  479. bool retried = false;
  480. do
  481. {
  482. lock (CScodeProvider)
  483. {
  484. results = CScodeProvider.CompileAssemblyFromSource(
  485. parameters, Script);
  486. }
  487. // Deal with an occasional segv in the compiler.
  488. // Rarely, if ever, occurs twice in succession.
  489. // Line # == 0 and no file name are indications that
  490. // this is a native stack trace rather than a normal
  491. // error log.
  492. if (results.Errors.Count > 0)
  493. {
  494. if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
  495. results.Errors[0].Line == 0)
  496. {
  497. // System.Console.WriteLine("retrying failed compilation");
  498. retried = true;
  499. }
  500. else
  501. {
  502. complete = true;
  503. }
  504. }
  505. else
  506. {
  507. complete = true;
  508. }
  509. } while (!complete);
  510. break;
  511. case enumCompileType.js:
  512. results = JScodeProvider.CompileAssemblyFromSource(
  513. parameters, Script);
  514. break;
  515. case enumCompileType.yp:
  516. results = YPcodeProvider.CompileAssemblyFromSource(
  517. parameters, Script);
  518. break;
  519. default:
  520. throw new Exception("Compiler is not able to recongnize "+
  521. "language type \"" + lang.ToString() + "\"");
  522. }
  523. // Check result
  524. // Go through errors
  525. //
  526. // WARNINGS AND ERRORS
  527. //
  528. bool hadErrors = false;
  529. string errtext = String.Empty;
  530. if (results.Errors.Count > 0)
  531. {
  532. foreach (CompilerError CompErr in results.Errors)
  533. {
  534. string severity = CompErr.IsWarning ? "Warning" : "Error";
  535. KeyValuePair<int, int> lslPos;
  536. // Show 5 errors max, but check entire list for errors
  537. if (severity == "Error")
  538. {
  539. lslPos = FindErrorPosition(CompErr.Line, CompErr.Column);
  540. string text = CompErr.ErrorText;
  541. // Use LSL type names
  542. if (lang == enumCompileType.lsl)
  543. text = ReplaceTypes(CompErr.ErrorText);
  544. // The Second Life viewer's script editor begins
  545. // countingn lines and columns at 0, so we subtract 1.
  546. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  547. lslPos.Key - 1, lslPos.Value - 1,
  548. CompErr.ErrorNumber, text, severity);
  549. hadErrors = true;
  550. }
  551. }
  552. }
  553. if (hadErrors)
  554. {
  555. throw new Exception(errtext);
  556. }
  557. // On today's highly asynchronous systems, the result of
  558. // the compile may not be immediately apparent. Wait a
  559. // reasonable amount of time before giving up on it.
  560. if (!File.Exists(OutFile))
  561. {
  562. for (int i=0; i<20 && !File.Exists(OutFile); i++)
  563. {
  564. System.Threading.Thread.Sleep(250);
  565. }
  566. // One final chance...
  567. if (!File.Exists(OutFile))
  568. {
  569. errtext = String.Empty;
  570. errtext += "No compile error. But not able to locate compiled file.";
  571. throw new Exception(errtext);
  572. }
  573. }
  574. // m_log.DebugFormat("[Compiler] Compiled new assembly "+
  575. // "for {0}", asset);
  576. // Because windows likes to perform exclusive locks, we simply
  577. // write out a textual representation of the file here
  578. //
  579. // Read the binary file into a buffer
  580. //
  581. FileInfo fi = new FileInfo(OutFile);
  582. if (fi == null)
  583. {
  584. errtext = String.Empty;
  585. errtext += "No compile error. But not able to stat file.";
  586. throw new Exception(errtext);
  587. }
  588. Byte[] data = new Byte[fi.Length];
  589. try
  590. {
  591. FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
  592. fs.Read(data, 0, data.Length);
  593. fs.Close();
  594. }
  595. catch (Exception)
  596. {
  597. errtext = String.Empty;
  598. errtext += "No compile error. But not able to open file.";
  599. throw new Exception(errtext);
  600. }
  601. // Convert to base64
  602. //
  603. string filetext = System.Convert.ToBase64String(data);
  604. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  605. Byte[] buf = enc.GetBytes(filetext);
  606. FileStream sfs = File.Create(OutFile+".text");
  607. sfs.Write(buf, 0, buf.Length);
  608. sfs.Close();
  609. string posmap = String.Empty;
  610. if (m_positionMap != null)
  611. {
  612. foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in m_positionMap)
  613. {
  614. KeyValuePair<int, int> k = kvp.Key;
  615. KeyValuePair<int, int> v = kvp.Value;
  616. posmap += String.Format("{0},{1},{2},{3}\n",
  617. k.Key, k.Value, v.Key, v.Value);
  618. }
  619. }
  620. buf = enc.GetBytes(posmap);
  621. FileStream mfs = File.Create(OutFile+".map");
  622. mfs.Write(buf, 0, buf.Length);
  623. mfs.Close();
  624. return OutFile;
  625. }
  626. public KeyValuePair<int, int> FindErrorPosition(int line, int col)
  627. {
  628. return FindErrorPosition(line, col, m_positionMap);
  629. }
  630. private class kvpSorter : IComparer<KeyValuePair<int,int>>
  631. {
  632. public int Compare(KeyValuePair<int,int> a,
  633. KeyValuePair<int,int> b)
  634. {
  635. return a.Key.CompareTo(b.Key);
  636. }
  637. }
  638. public static KeyValuePair<int, int> FindErrorPosition(int line,
  639. int col, Dictionary<KeyValuePair<int, int>,
  640. KeyValuePair<int, int>> positionMap)
  641. {
  642. if (positionMap == null || positionMap.Count == 0)
  643. return new KeyValuePair<int, int>(line, col);
  644. KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
  645. if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
  646. out ret))
  647. return ret;
  648. List<KeyValuePair<int,int>> sorted =
  649. new List<KeyValuePair<int,int>>(positionMap.Keys);
  650. sorted.Sort(new kvpSorter());
  651. int l = 1;
  652. int c = 1;
  653. foreach (KeyValuePair<int, int> cspos in sorted)
  654. {
  655. if (cspos.Key >= line)
  656. {
  657. if (cspos.Key > line)
  658. return new KeyValuePair<int, int>(l, c);
  659. if (cspos.Value > col)
  660. return new KeyValuePair<int, int>(l, c);
  661. c = cspos.Value;
  662. if (c == 0)
  663. c++;
  664. }
  665. else
  666. {
  667. l = cspos.Key;
  668. }
  669. }
  670. return new KeyValuePair<int, int>(l, c);
  671. }
  672. string ReplaceTypes(string message)
  673. {
  674. message = message.Replace(
  675. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
  676. "string");
  677. message = message.Replace(
  678. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
  679. "integer");
  680. message = message.Replace(
  681. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
  682. "float");
  683. message = message.Replace(
  684. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
  685. "list");
  686. return message;
  687. }
  688. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap()
  689. {
  690. if (m_positionMap == null)
  691. return null;
  692. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ret =
  693. new Dictionary<KeyValuePair<int,int>, KeyValuePair<int, int>>();
  694. foreach (KeyValuePair<int, int> kvp in m_positionMap.Keys)
  695. ret.Add(kvp, m_positionMap[kvp]);
  696. return ret;
  697. }
  698. private void ReadMapFile(string filename)
  699. {
  700. try
  701. {
  702. StreamReader r = File.OpenText(filename);
  703. m_positionMap = new Dictionary<KeyValuePair<int,int>, KeyValuePair<int, int>>();
  704. string line;
  705. while ((line = r.ReadLine()) != null)
  706. {
  707. String[] parts = line.Split(new Char[] {','});
  708. int kk = System.Convert.ToInt32(parts[0]);
  709. int kv = System.Convert.ToInt32(parts[1]);
  710. int vk = System.Convert.ToInt32(parts[2]);
  711. int vv = System.Convert.ToInt32(parts[3]);
  712. KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
  713. KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
  714. m_positionMap[k] = v;
  715. }
  716. }
  717. catch
  718. {
  719. }
  720. }
  721. }
  722. }