1
0

Compiler.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 string GetCompilerOutput(string assetID)
  235. {
  236. return Path.Combine(ScriptEnginesPath, Path.Combine(
  237. m_scriptEngine.World.RegionInfo.RegionID.ToString(),
  238. FilePrefix + "_compiled_" + assetID + ".dll"));
  239. }
  240. public string GetCompilerOutput(UUID assetID)
  241. {
  242. return GetCompilerOutput(assetID.ToString());
  243. }
  244. /// <summary>
  245. /// Converts script from LSL to CS and calls CompileFromCSText
  246. /// </summary>
  247. /// <param name="Script">LSL script</param>
  248. /// <returns>Filename to .dll assembly</returns>
  249. public void PerformScriptCompile(string Script, string asset, UUID ownerUUID,
  250. out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
  251. {
  252. linemap = null;
  253. m_warnings.Clear();
  254. assembly = GetCompilerOutput(asset);
  255. if (!Directory.Exists(ScriptEnginesPath))
  256. {
  257. try
  258. {
  259. Directory.CreateDirectory(ScriptEnginesPath);
  260. }
  261. catch (Exception)
  262. {
  263. }
  264. }
  265. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  266. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  267. {
  268. try
  269. {
  270. Directory.CreateDirectory(ScriptEnginesPath);
  271. }
  272. catch (Exception)
  273. {
  274. }
  275. }
  276. // Don't recompile if we already have it
  277. // Performing 3 file exists tests for every script can still be slow
  278. if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
  279. {
  280. // If we have already read this linemap file, then it will be in our dictionary.
  281. // Don't build another copy of the dictionary (saves memory) and certainly
  282. // don't keep reading the same file from disk multiple times.
  283. if (!m_lineMaps.ContainsKey(assembly))
  284. m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
  285. linemap = m_lineMaps[assembly];
  286. return;
  287. }
  288. if (Script == String.Empty)
  289. {
  290. throw new Exception("Cannot find script assembly and no script text present");
  291. }
  292. enumCompileType language = DefaultCompileLanguage;
  293. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  294. language = enumCompileType.cs;
  295. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  296. {
  297. language = enumCompileType.vb;
  298. // We need to remove //vb, it won't compile with that
  299. Script = Script.Substring(4, Script.Length - 4);
  300. }
  301. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  302. language = enumCompileType.lsl;
  303. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  304. language = enumCompileType.js;
  305. if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
  306. language = enumCompileType.yp;
  307. if (!AllowedCompilers.ContainsKey(language.ToString()))
  308. {
  309. // Not allowed to compile to this language!
  310. string errtext = String.Empty;
  311. errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  312. throw new Exception(errtext);
  313. }
  314. if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
  315. {
  316. // Not allowed to compile to this language!
  317. string errtext = String.Empty;
  318. errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
  319. throw new Exception(errtext);
  320. }
  321. string compileScript = Script;
  322. if (language == enumCompileType.lsl)
  323. {
  324. // Its LSL, convert it to C#
  325. LSL_Converter = (ICodeConverter)new CSCodeGenerator();
  326. compileScript = LSL_Converter.Convert(Script);
  327. // copy converter warnings into our warnings.
  328. foreach (string warning in LSL_Converter.GetWarnings())
  329. {
  330. AddWarning(warning);
  331. }
  332. linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
  333. // Write the linemap to a file and save it in our dictionary for next time.
  334. m_lineMaps[assembly] = linemap;
  335. WriteMapFile(assembly + ".map", linemap);
  336. }
  337. if (language == enumCompileType.yp)
  338. {
  339. // Its YP, convert it to C#
  340. compileScript = YP_Converter.Convert(Script);
  341. }
  342. switch (language)
  343. {
  344. case enumCompileType.cs:
  345. case enumCompileType.lsl:
  346. compileScript = CreateCSCompilerScript(compileScript);
  347. break;
  348. case enumCompileType.vb:
  349. compileScript = CreateVBCompilerScript(compileScript);
  350. break;
  351. // case enumCompileType.js:
  352. // compileScript = CreateJSCompilerScript(compileScript);
  353. // break;
  354. case enumCompileType.yp:
  355. compileScript = CreateYPCompilerScript(compileScript);
  356. break;
  357. }
  358. assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
  359. return;
  360. }
  361. public string[] GetWarnings()
  362. {
  363. return m_warnings.ToArray();
  364. }
  365. private void AddWarning(string warning)
  366. {
  367. if (!m_warnings.Contains(warning))
  368. {
  369. m_warnings.Add(warning);
  370. }
  371. }
  372. // private static string CreateJSCompilerScript(string compileScript)
  373. // {
  374. // compileScript = String.Empty +
  375. // "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
  376. // "package SecondLife {\r\n" +
  377. // "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  378. // compileScript +
  379. // "} }\r\n";
  380. // return compileScript;
  381. // }
  382. private static string CreateCSCompilerScript(string compileScript)
  383. {
  384. compileScript = String.Empty +
  385. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  386. String.Empty + "namespace SecondLife { " +
  387. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  388. @"public Script() { } " +
  389. compileScript +
  390. "} }\r\n";
  391. return compileScript;
  392. }
  393. private static string CreateYPCompilerScript(string compileScript)
  394. {
  395. compileScript = String.Empty +
  396. "using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " +
  397. "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
  398. String.Empty + "namespace SecondLife { " +
  399. String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  400. //@"public Script() { } " +
  401. @"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " +
  402. @"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " +
  403. compileScript +
  404. "} }\r\n";
  405. return compileScript;
  406. }
  407. private static string CreateVBCompilerScript(string compileScript)
  408. {
  409. compileScript = String.Empty +
  410. "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
  411. String.Empty + "NameSpace SecondLife:" +
  412. String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " +
  413. "\r\nPublic Sub New()\r\nEnd Sub: " +
  414. compileScript +
  415. ":End Class :End Namespace\r\n";
  416. return compileScript;
  417. }
  418. /// <summary>
  419. /// Compile .NET script to .Net assembly (.dll)
  420. /// </summary>
  421. /// <param name="Script">CS script</param>
  422. /// <returns>Filename to .dll assembly</returns>
  423. internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
  424. {
  425. string ext = "." + lang.ToString();
  426. // Output assembly name
  427. scriptCompileCounter++;
  428. try
  429. {
  430. File.Delete(assembly);
  431. }
  432. catch (Exception e) // NOTLEGIT - Should be just FileIOException
  433. {
  434. throw new Exception("Unable to delete old existing " +
  435. "script-file before writing new. Compile aborted: " +
  436. e.ToString());
  437. }
  438. // DEBUG - write source to disk
  439. if (WriteScriptSourceToDebugFile)
  440. {
  441. string srcFileName = FilePrefix + "_source_" +
  442. Path.GetFileNameWithoutExtension(assembly) + ext;
  443. try
  444. {
  445. File.WriteAllText(Path.Combine(Path.Combine(
  446. ScriptEnginesPath,
  447. m_scriptEngine.World.RegionInfo.RegionID.ToString()),
  448. srcFileName), Script);
  449. }
  450. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  451. {
  452. m_log.Error("[Compiler]: Exception while " +
  453. "trying to write script source to file \"" +
  454. srcFileName + "\": " + ex.ToString());
  455. }
  456. }
  457. // Do actual compile
  458. CompilerParameters parameters = new CompilerParameters();
  459. parameters.IncludeDebugInformation = true;
  460. string rootPath =
  461. Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  462. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  463. "OpenSim.Region.ScriptEngine.Shared.dll"));
  464. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  465. "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
  466. if (lang == enumCompileType.yp)
  467. {
  468. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  469. "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
  470. }
  471. parameters.GenerateExecutable = false;
  472. parameters.OutputAssembly = assembly;
  473. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  474. //parameters.WarningLevel = 1; // Should be 4?
  475. parameters.TreatWarningsAsErrors = false;
  476. CompilerResults results;
  477. switch (lang)
  478. {
  479. case enumCompileType.vb:
  480. results = VBcodeProvider.CompileAssemblyFromSource(
  481. parameters, Script);
  482. break;
  483. case enumCompileType.cs:
  484. case enumCompileType.lsl:
  485. bool complete = false;
  486. bool retried = false;
  487. do
  488. {
  489. lock (CScodeProvider)
  490. {
  491. results = CScodeProvider.CompileAssemblyFromSource(
  492. parameters, Script);
  493. }
  494. // Deal with an occasional segv in the compiler.
  495. // Rarely, if ever, occurs twice in succession.
  496. // Line # == 0 and no file name are indications that
  497. // this is a native stack trace rather than a normal
  498. // error log.
  499. if (results.Errors.Count > 0)
  500. {
  501. if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
  502. results.Errors[0].Line == 0)
  503. {
  504. // System.Console.WriteLine("retrying failed compilation");
  505. retried = true;
  506. }
  507. else
  508. {
  509. complete = true;
  510. }
  511. }
  512. else
  513. {
  514. complete = true;
  515. }
  516. } while (!complete);
  517. break;
  518. // case enumCompileType.js:
  519. // results = JScodeProvider.CompileAssemblyFromSource(
  520. // parameters, Script);
  521. // break;
  522. case enumCompileType.yp:
  523. results = YPcodeProvider.CompileAssemblyFromSource(
  524. parameters, Script);
  525. break;
  526. default:
  527. throw new Exception("Compiler is not able to recongnize " +
  528. "language type \"" + lang.ToString() + "\"");
  529. }
  530. // Check result
  531. // Go through errors
  532. //
  533. // WARNINGS AND ERRORS
  534. //
  535. bool hadErrors = false;
  536. string errtext = String.Empty;
  537. if (results.Errors.Count > 0)
  538. {
  539. foreach (CompilerError CompErr in results.Errors)
  540. {
  541. string severity = CompErr.IsWarning ? "Warning" : "Error";
  542. KeyValuePair<int, int> lslPos;
  543. // Show 5 errors max, but check entire list for errors
  544. if (severity == "Error")
  545. {
  546. lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
  547. string text = CompErr.ErrorText;
  548. // Use LSL type names
  549. if (lang == enumCompileType.lsl)
  550. text = ReplaceTypes(CompErr.ErrorText);
  551. // The Second Life viewer's script editor begins
  552. // countingn lines and columns at 0, so we subtract 1.
  553. errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
  554. lslPos.Key - 1, lslPos.Value - 1,
  555. CompErr.ErrorNumber, text, severity);
  556. hadErrors = true;
  557. }
  558. }
  559. }
  560. if (hadErrors)
  561. {
  562. throw new Exception(errtext);
  563. }
  564. // On today's highly asynchronous systems, the result of
  565. // the compile may not be immediately apparent. Wait a
  566. // reasonable amount of time before giving up on it.
  567. if (!File.Exists(assembly))
  568. {
  569. for (int i = 0; i < 20 && !File.Exists(assembly); i++)
  570. {
  571. System.Threading.Thread.Sleep(250);
  572. }
  573. // One final chance...
  574. if (!File.Exists(assembly))
  575. {
  576. errtext = String.Empty;
  577. errtext += "No compile error. But not able to locate compiled file.";
  578. throw new Exception(errtext);
  579. }
  580. }
  581. // m_log.DebugFormat("[Compiler] Compiled new assembly "+
  582. // "for {0}", asset);
  583. // Because windows likes to perform exclusive locks, we simply
  584. // write out a textual representation of the file here
  585. //
  586. // Read the binary file into a buffer
  587. //
  588. FileInfo fi = new FileInfo(assembly);
  589. if (fi == null)
  590. {
  591. errtext = String.Empty;
  592. errtext += "No compile error. But not able to stat file.";
  593. throw new Exception(errtext);
  594. }
  595. Byte[] data = new Byte[fi.Length];
  596. try
  597. {
  598. FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
  599. fs.Read(data, 0, data.Length);
  600. fs.Close();
  601. }
  602. catch (Exception)
  603. {
  604. errtext = String.Empty;
  605. errtext += "No compile error. But not able to open file.";
  606. throw new Exception(errtext);
  607. }
  608. // Convert to base64
  609. //
  610. string filetext = System.Convert.ToBase64String(data);
  611. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  612. Byte[] buf = enc.GetBytes(filetext);
  613. FileStream sfs = File.Create(assembly + ".text");
  614. sfs.Write(buf, 0, buf.Length);
  615. sfs.Close();
  616. return assembly;
  617. }
  618. private class kvpSorter : IComparer<KeyValuePair<int, int>>
  619. {
  620. public int Compare(KeyValuePair<int, int> a,
  621. KeyValuePair<int, int> b)
  622. {
  623. return a.Key.CompareTo(b.Key);
  624. }
  625. }
  626. public static KeyValuePair<int, int> FindErrorPosition(int line,
  627. int col, Dictionary<KeyValuePair<int, int>,
  628. KeyValuePair<int, int>> positionMap)
  629. {
  630. if (positionMap == null || positionMap.Count == 0)
  631. return new KeyValuePair<int, int>(line, col);
  632. KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
  633. if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
  634. out ret))
  635. return ret;
  636. List<KeyValuePair<int, int>> sorted =
  637. new List<KeyValuePair<int, int>>(positionMap.Keys);
  638. sorted.Sort(new kvpSorter());
  639. int l = 1;
  640. int c = 1;
  641. foreach (KeyValuePair<int, int> cspos in sorted)
  642. {
  643. if (cspos.Key >= line)
  644. {
  645. if (cspos.Key > line)
  646. return new KeyValuePair<int, int>(l, c);
  647. if (cspos.Value > col)
  648. return new KeyValuePair<int, int>(l, c);
  649. c = cspos.Value;
  650. if (c == 0)
  651. c++;
  652. }
  653. else
  654. {
  655. l = cspos.Key;
  656. }
  657. }
  658. return new KeyValuePair<int, int>(l, c);
  659. }
  660. string ReplaceTypes(string message)
  661. {
  662. message = message.Replace(
  663. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
  664. "string");
  665. message = message.Replace(
  666. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
  667. "integer");
  668. message = message.Replace(
  669. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
  670. "float");
  671. message = message.Replace(
  672. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
  673. "list");
  674. return message;
  675. }
  676. private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
  677. {
  678. string mapstring = String.Empty;
  679. foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
  680. {
  681. KeyValuePair<int, int> k = kvp.Key;
  682. KeyValuePair<int, int> v = kvp.Value;
  683. mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
  684. }
  685. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  686. Byte[] mapbytes = enc.GetBytes(mapstring);
  687. FileStream mfs = File.Create(filename);
  688. mfs.Write(mapbytes, 0, mapbytes.Length);
  689. mfs.Close();
  690. }
  691. private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
  692. {
  693. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  694. try
  695. {
  696. StreamReader r = File.OpenText(filename);
  697. linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
  698. string line;
  699. while ((line = r.ReadLine()) != null)
  700. {
  701. String[] parts = line.Split(new Char[] { ',' });
  702. int kk = System.Convert.ToInt32(parts[0]);
  703. int kv = System.Convert.ToInt32(parts[1]);
  704. int vk = System.Convert.ToInt32(parts[2]);
  705. int vv = System.Convert.ToInt32(parts[3]);
  706. KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
  707. KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
  708. linemap[k] = v;
  709. }
  710. }
  711. catch
  712. {
  713. linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
  714. }
  715. return linemap;
  716. }
  717. }
  718. }