Compiler.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.CodeDom.Compiler;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.Reflection;
  32. using System.IO;
  33. using System.Text;
  34. using Microsoft.CSharp;
  35. //using Microsoft.JScript;
  36. using Microsoft.VisualBasic;
  37. using log4net;
  38. using OpenSim.Region.Framework.Interfaces;
  39. using OpenSim.Region.ScriptEngine.Interfaces;
  40. using OpenMetaverse;
  41. namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
  42. {
  43. public class Compiler : ICompiler
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. // * Uses "LSL2Converter" to convert LSL to C# if necessary.
  47. // * Compiles C#-code into an assembly
  48. // * Returns assembly name ready for AppDomain load.
  49. //
  50. // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
  51. //
  52. internal enum enumCompileType
  53. {
  54. lsl = 0,
  55. cs = 1,
  56. vb = 2,
  57. js = 3,
  58. yp = 4
  59. }
  60. /// <summary>
  61. /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
  62. /// </summary>
  63. public int LinesToRemoveOnError = 3;
  64. private enumCompileType DefaultCompileLanguage;
  65. private bool WriteScriptSourceToDebugFile;
  66. private bool CompileWithDebugInformation;
  67. private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
  68. private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
  69. private bool m_insertCoopTerminationCalls;
  70. private string FilePrefix;
  71. private string ScriptEnginesPath = null;
  72. // mapping between LSL and C# line/column numbers
  73. private ICodeConverter LSL_Converter;
  74. private List<string> m_warnings = new List<string>();
  75. // private object m_syncy = new object();
  76. private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  77. private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
  78. // private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
  79. private static UInt64 scriptCompileCounter = 0; // And a counter
  80. public IScriptEngine m_scriptEngine;
  81. private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
  82. new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
  83. public bool in_startup = true;
  84. public Compiler(IScriptEngine scriptEngine)
  85. {
  86. m_scriptEngine = scriptEngine;
  87. ScriptEnginesPath = scriptEngine.ScriptEnginePath;
  88. ReadConfig();
  89. }
  90. public void ReadConfig()
  91. {
  92. // Get some config
  93. WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
  94. CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
  95. bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
  96. m_insertCoopTerminationCalls = m_scriptEngine.Config.GetString("ScriptStopStrategy", "abort") == "co-op";
  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. IScriptModuleComms comms = m_scriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
  263. linemap = null;
  264. m_warnings.Clear();
  265. assembly = GetCompilerOutput(asset);
  266. if (!Directory.Exists(ScriptEnginesPath))
  267. {
  268. try
  269. {
  270. Directory.CreateDirectory(ScriptEnginesPath);
  271. }
  272. catch (Exception)
  273. {
  274. }
  275. }
  276. if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
  277. m_scriptEngine.World.RegionInfo.RegionID.ToString())))
  278. {
  279. try
  280. {
  281. Directory.CreateDirectory(ScriptEnginesPath);
  282. }
  283. catch (Exception)
  284. {
  285. }
  286. }
  287. // Don't recompile if we already have it
  288. // Performing 3 file exists tests for every script can still be slow
  289. if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
  290. {
  291. // If we have already read this linemap file, then it will be in our dictionary.
  292. // Don't build another copy of the dictionary (saves memory) and certainly
  293. // don't keep reading the same file from disk multiple times.
  294. if (!m_lineMaps.ContainsKey(assembly))
  295. m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
  296. linemap = m_lineMaps[assembly];
  297. return;
  298. }
  299. if (Script == String.Empty)
  300. {
  301. throw new Exception("Cannot find script assembly and no script text present");
  302. }
  303. enumCompileType language = DefaultCompileLanguage;
  304. if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
  305. language = enumCompileType.cs;
  306. if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
  307. {
  308. language = enumCompileType.vb;
  309. // We need to remove //vb, it won't compile with that
  310. Script = Script.Substring(4, Script.Length - 4);
  311. }
  312. if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
  313. language = enumCompileType.lsl;
  314. if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
  315. language = enumCompileType.js;
  316. if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
  317. language = enumCompileType.yp;
  318. // m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
  319. if (!AllowedCompilers.ContainsKey(language.ToString()))
  320. {
  321. // Not allowed to compile to this language!
  322. string errtext = String.Empty;
  323. errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
  324. throw new Exception(errtext);
  325. }
  326. if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
  327. {
  328. // Not allowed to compile to this language!
  329. string errtext = String.Empty;
  330. errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
  331. throw new Exception(errtext);
  332. }
  333. string compileScript = Script;
  334. if (language == enumCompileType.lsl)
  335. {
  336. // Its LSL, convert it to C#
  337. LSL_Converter = (ICodeConverter)new CSCodeGenerator(comms, m_insertCoopTerminationCalls);
  338. compileScript = LSL_Converter.Convert(Script);
  339. // copy converter warnings into our warnings.
  340. foreach (string warning in LSL_Converter.GetWarnings())
  341. {
  342. AddWarning(warning);
  343. }
  344. linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
  345. // Write the linemap to a file and save it in our dictionary for next time.
  346. m_lineMaps[assembly] = linemap;
  347. WriteMapFile(assembly + ".map", linemap);
  348. }
  349. switch (language)
  350. {
  351. case enumCompileType.cs:
  352. case enumCompileType.lsl:
  353. compileScript = CreateCSCompilerScript(
  354. compileScript,
  355. m_scriptEngine.ScriptClassName,
  356. m_scriptEngine.ScriptBaseClassName,
  357. m_scriptEngine.ScriptBaseClassParameters);
  358. break;
  359. case enumCompileType.vb:
  360. compileScript = CreateVBCompilerScript(
  361. compileScript, m_scriptEngine.ScriptClassName, m_scriptEngine.ScriptBaseClassName);
  362. break;
  363. }
  364. assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
  365. }
  366. public string[] GetWarnings()
  367. {
  368. return m_warnings.ToArray();
  369. }
  370. private void AddWarning(string warning)
  371. {
  372. if (!m_warnings.Contains(warning))
  373. {
  374. m_warnings.Add(warning);
  375. }
  376. }
  377. // private static string CreateJSCompilerScript(string compileScript)
  378. // {
  379. // compileScript = String.Empty +
  380. // "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
  381. // "package SecondLife {\r\n" +
  382. // "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
  383. // compileScript +
  384. // "} }\r\n";
  385. // return compileScript;
  386. // }
  387. private static string CreateCSCompilerScript(
  388. string compileScript, string className, string baseClassName, ParameterInfo[] constructorParameters)
  389. {
  390. compileScript = string.Format(
  391. @"using OpenSim.Region.ScriptEngine.Shared;
  392. using System.Collections.Generic;
  393. namespace SecondLife
  394. {{
  395. public class {0} : {1}
  396. {{
  397. public {0}({2}) : base({3}) {{}}
  398. {4}
  399. }}
  400. }}",
  401. className,
  402. baseClassName,
  403. constructorParameters != null
  404. ? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
  405. : "",
  406. constructorParameters != null
  407. ? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
  408. : "",
  409. compileScript);
  410. return compileScript;
  411. }
  412. private static string CreateVBCompilerScript(string compileScript, string className, string baseClassName)
  413. {
  414. compileScript = String.Empty +
  415. "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
  416. String.Empty + "NameSpace SecondLife:" +
  417. String.Empty + "Public Class " + className + ": Inherits " + baseClassName +
  418. "\r\nPublic Sub New()\r\nEnd Sub: " +
  419. compileScript +
  420. ":End Class :End Namespace\r\n";
  421. return compileScript;
  422. }
  423. /// <summary>
  424. /// Compile .NET script to .Net assembly (.dll)
  425. /// </summary>
  426. /// <param name="Script">CS script</param>
  427. /// <returns>Filename to .dll assembly</returns>
  428. internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
  429. {
  430. // m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
  431. string ext = "." + lang.ToString();
  432. // Output assembly name
  433. scriptCompileCounter++;
  434. try
  435. {
  436. File.Delete(assembly);
  437. }
  438. catch (Exception e) // NOTLEGIT - Should be just FileIOException
  439. {
  440. throw new Exception("Unable to delete old existing " +
  441. "script-file before writing new. Compile aborted: " +
  442. e.ToString());
  443. }
  444. // DEBUG - write source to disk
  445. if (WriteScriptSourceToDebugFile)
  446. {
  447. string srcFileName = FilePrefix + "_source_" +
  448. Path.GetFileNameWithoutExtension(assembly) + ext;
  449. try
  450. {
  451. File.WriteAllText(Path.Combine(Path.Combine(
  452. ScriptEnginesPath,
  453. m_scriptEngine.World.RegionInfo.RegionID.ToString()),
  454. srcFileName), Script);
  455. }
  456. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  457. {
  458. m_log.Error("[Compiler]: Exception while " +
  459. "trying to write script source to file \"" +
  460. srcFileName + "\": " + ex.ToString());
  461. }
  462. }
  463. // Do actual compile
  464. CompilerParameters parameters = new CompilerParameters();
  465. parameters.IncludeDebugInformation = true;
  466. string rootPath = AppDomain.CurrentDomain.BaseDirectory;
  467. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  468. "OpenSim.Region.ScriptEngine.Shared.dll"));
  469. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  470. "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
  471. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  472. "OpenMetaverseTypes.dll"));
  473. if (m_scriptEngine.ScriptReferencedAssemblies != null)
  474. Array.ForEach<string>(
  475. m_scriptEngine.ScriptReferencedAssemblies,
  476. a => parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, a)));
  477. if (lang == enumCompileType.yp)
  478. {
  479. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
  480. "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
  481. }
  482. parameters.GenerateExecutable = false;
  483. parameters.OutputAssembly = assembly;
  484. parameters.IncludeDebugInformation = CompileWithDebugInformation;
  485. //parameters.WarningLevel = 1; // Should be 4?
  486. parameters.TreatWarningsAsErrors = false;
  487. CompilerResults results;
  488. switch (lang)
  489. {
  490. case enumCompileType.vb:
  491. results = VBcodeProvider.CompileAssemblyFromSource(
  492. parameters, Script);
  493. break;
  494. case enumCompileType.cs:
  495. case enumCompileType.lsl:
  496. bool complete = false;
  497. bool retried = false;
  498. do
  499. {
  500. lock (CScodeProvider)
  501. {
  502. results = CScodeProvider.CompileAssemblyFromSource(
  503. parameters, Script);
  504. }
  505. // Deal with an occasional segv in the compiler.
  506. // Rarely, if ever, occurs twice in succession.
  507. // Line # == 0 and no file name are indications that
  508. // this is a native stack trace rather than a normal
  509. // error log.
  510. if (results.Errors.Count > 0)
  511. {
  512. if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
  513. results.Errors[0].Line == 0)
  514. {
  515. // System.Console.WriteLine("retrying failed compilation");
  516. retried = true;
  517. }
  518. else
  519. {
  520. complete = true;
  521. }
  522. }
  523. else
  524. {
  525. complete = true;
  526. }
  527. } while (!complete);
  528. break;
  529. default:
  530. throw new Exception("Compiler is not able to recongnize " +
  531. "language type \"" + lang.ToString() + "\"");
  532. }
  533. // foreach (Type type in results.CompiledAssembly.GetTypes())
  534. // {
  535. // foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
  536. // {
  537. // m_log.DebugFormat("[COMPILER]: {0}.{1}", type.FullName, method.Name);
  538. // }
  539. // }
  540. //
  541. // WARNINGS AND ERRORS
  542. //
  543. bool hadErrors = false;
  544. string errtext = String.Empty;
  545. if (results.Errors.Count > 0)
  546. {
  547. foreach (CompilerError CompErr in results.Errors)
  548. {
  549. string severity = CompErr.IsWarning ? "Warning" : "Error";
  550. KeyValuePair<int, int> errorPos;
  551. // Show 5 errors max, but check entire list for errors
  552. if (severity == "Error")
  553. {
  554. // C# scripts will not have a linemap since theres no line translation involved.
  555. if (!m_lineMaps.ContainsKey(assembly))
  556. errorPos = new KeyValuePair<int, int>(CompErr.Line, CompErr.Column);
  557. else
  558. errorPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
  559. string text = CompErr.ErrorText;
  560. // Use LSL type names
  561. if (lang == enumCompileType.lsl)
  562. text = ReplaceTypes(CompErr.ErrorText);
  563. // The Second Life viewer's script editor begins
  564. // countingn lines and columns at 0, so we subtract 1.
  565. errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
  566. errorPos.Key - 1, errorPos.Value - 1,
  567. CompErr.ErrorNumber, text, severity);
  568. hadErrors = true;
  569. }
  570. }
  571. }
  572. if (hadErrors)
  573. {
  574. throw new Exception(errtext);
  575. }
  576. // On today's highly asynchronous systems, the result of
  577. // the compile may not be immediately apparent. Wait a
  578. // reasonable amount of time before giving up on it.
  579. if (!File.Exists(assembly))
  580. {
  581. for (int i = 0; i < 20 && !File.Exists(assembly); i++)
  582. {
  583. System.Threading.Thread.Sleep(250);
  584. }
  585. // One final chance...
  586. if (!File.Exists(assembly))
  587. {
  588. errtext = String.Empty;
  589. errtext += "No compile error. But not able to locate compiled file.";
  590. throw new Exception(errtext);
  591. }
  592. }
  593. // m_log.DebugFormat("[Compiler] Compiled new assembly "+
  594. // "for {0}", asset);
  595. // Because windows likes to perform exclusive locks, we simply
  596. // write out a textual representation of the file here
  597. //
  598. // Read the binary file into a buffer
  599. //
  600. FileInfo fi = new FileInfo(assembly);
  601. if (fi == null)
  602. {
  603. errtext = String.Empty;
  604. errtext += "No compile error. But not able to stat file.";
  605. throw new Exception(errtext);
  606. }
  607. Byte[] data = new Byte[fi.Length];
  608. try
  609. {
  610. FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
  611. fs.Read(data, 0, data.Length);
  612. fs.Close();
  613. }
  614. catch (Exception)
  615. {
  616. errtext = String.Empty;
  617. errtext += "No compile error. But not able to open file.";
  618. throw new Exception(errtext);
  619. }
  620. // Convert to base64
  621. //
  622. string filetext = System.Convert.ToBase64String(data);
  623. Byte[] buf = Encoding.ASCII.GetBytes(filetext);
  624. FileStream sfs = File.Create(assembly + ".text");
  625. sfs.Write(buf, 0, buf.Length);
  626. sfs.Close();
  627. return assembly;
  628. }
  629. private class kvpSorter : IComparer<KeyValuePair<int, int>>
  630. {
  631. public int Compare(KeyValuePair<int, int> a,
  632. KeyValuePair<int, int> b)
  633. {
  634. return a.Key.CompareTo(b.Key);
  635. }
  636. }
  637. public static KeyValuePair<int, int> FindErrorPosition(int line,
  638. int col, Dictionary<KeyValuePair<int, int>,
  639. KeyValuePair<int, int>> positionMap)
  640. {
  641. if (positionMap == null || positionMap.Count == 0)
  642. return new KeyValuePair<int, int>(line, col);
  643. KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
  644. if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
  645. out ret))
  646. return ret;
  647. List<KeyValuePair<int, int>> sorted =
  648. new List<KeyValuePair<int, int>>(positionMap.Keys);
  649. sorted.Sort(new kvpSorter());
  650. int l = 1;
  651. int c = 1;
  652. foreach (KeyValuePair<int, int> cspos in sorted)
  653. {
  654. if (cspos.Key >= line)
  655. {
  656. if (cspos.Key > line)
  657. return new KeyValuePair<int, int>(l, c);
  658. if (cspos.Value > col)
  659. return new KeyValuePair<int, int>(l, c);
  660. c = cspos.Value;
  661. if (c == 0)
  662. c++;
  663. }
  664. else
  665. {
  666. l = cspos.Key;
  667. }
  668. }
  669. return new KeyValuePair<int, int>(l, c);
  670. }
  671. string ReplaceTypes(string message)
  672. {
  673. message = message.Replace(
  674. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
  675. "string");
  676. message = message.Replace(
  677. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
  678. "integer");
  679. message = message.Replace(
  680. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
  681. "float");
  682. message = message.Replace(
  683. "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
  684. "list");
  685. return message;
  686. }
  687. private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
  688. {
  689. string mapstring = String.Empty;
  690. foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
  691. {
  692. KeyValuePair<int, int> k = kvp.Key;
  693. KeyValuePair<int, int> v = kvp.Value;
  694. mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
  695. }
  696. Byte[] mapbytes = Encoding.ASCII.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. }