1
0

Compiler.cs 34 KB

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