Compiler.cs 33 KB

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