Compiler.cs 34 KB

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