1
0

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