appdomains are gone. XEngine does not make much sense without them

This commit is contained in:
UbitUmarov
2022-10-02 11:38:50 +01:00
parent f6a47a9f47
commit 6ff8ecaae0
44 changed files with 13 additions and 43961 deletions

View File

@@ -232,7 +232,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
}
catch ( System.Threading.ThreadAbortException)
{
Thread.ResetAbort();
//Thread.ResetAbort();
running = false;
}
catch (Exception e)

View File

@@ -527,19 +527,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
m_sleepMsOnEmail = EMAIL_PAUSE_TIME * 1000;
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
protected SceneObjectPart MonitoringObject()
{
UUID m = m_host.ParentGroup.MonitoringObject;

View File

@@ -29,7 +29,6 @@ using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
@@ -83,19 +82,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
m_environment = m_ScriptEngine.World.RequestModuleInterface<IEnvironmentModule>();
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
//lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
//lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public Scene World
{
get { return m_ScriptEngine.World; }

View File

@@ -29,7 +29,6 @@ using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using log4net;
using OpenMetaverse;
@@ -86,19 +85,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
m_MODFunctionsEnabled = false;
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public Scene World
{
get { return m_ScriptEngine.World; }

View File

@@ -43,7 +43,6 @@ using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
@@ -250,19 +249,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
}
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public Scene World
{
get { return m_ScriptEngine.World; }

View File

@@ -29,7 +29,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics; //for [DebuggerNonUserCode]
using System.Reflection;
using System.Runtime.Remoting.Lifetime;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using log4net;

View File

@@ -27,7 +27,6 @@
using System;
using System.Diagnostics; //for [DebuggerNonUserCode]
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;

View File

@@ -26,7 +26,6 @@
*/
using System;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;

View File

@@ -26,7 +26,6 @@
*/
using System;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;

View File

@@ -26,7 +26,6 @@
*/
using System;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;

View File

@@ -26,45 +26,16 @@
*/
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics; //for [DebuggerNonUserCode]
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject, IScript
{
private Dictionary<string, MethodInfo> inits = new Dictionary<string, MethodInfo>();
// private ScriptSponsor m_sponser;
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
// Infinite
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
#if DEBUG
// For tracing GC while debugging
public static bool GCDummy = false;
~ScriptBaseClass()
{
GCDummy = true;
}
#endif
public ScriptBaseClass()
{

View File

@@ -1,57 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Text;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Runtime
{
public class ScriptSponsor : MarshalByRefObject, ISponsor
{
private bool m_closed = false;
public TimeSpan Renewal(ILease lease)
{
if (!m_closed)
return lease.InitialLeaseTime;
return TimeSpan.FromTicks(0);
}
public void Close() { m_closed = true; }
#if DEBUG
// For tracing GC while debugging
public static bool GCDummy = false;
~ScriptSponsor()
{
GCDummy = true;
}
#endif
}
}

View File

@@ -1,68 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
namespace OpenSim.Region.ScriptEngine.Shared
{
[Serializable]
public class AssemblyResolver : MarshalByRefObject
{
public static Assembly OnAssemblyResolve(object sender,
ResolveEventArgs args)
{
if (!(sender is System.AppDomain))
return null;
AppDomain myDomain = (AppDomain)sender;
string dirName = myDomain.FriendlyName;
string ScriptEnginesPath = myDomain.SetupInformation.PrivateBinPath;
string[] pathList = new string[] {"", "bin", ScriptEnginesPath,
Path.Combine(ScriptEnginesPath, dirName)};
string assemblyName = args.Name;
if (assemblyName.IndexOf(",") != -1)
assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
foreach (string s in pathList)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(s, assemblyName))+".dll";
// Console.WriteLine("Trying to resolve {0}", path);
if (File.Exists(path))
return Assembly.LoadFrom(path);
}
return null;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,91 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
/// <summary>
/// A container for all of the reserved C# words that are not also reserved words in LSL.
/// The words must be maintained in alphabetical order.
/// The words that are key words in lsl are picked up by the lsl compiler as errors.
/// The LSL reserved words have been left in the list as comments for completeness
/// </summary>
internal class CSReservedWords
{
private static List<string> reservedWords = new List<string>(new string[] {
"abstract","as",
"base","bool","break","byte",
"case","catch","char","checked","class","const","continue",
"decimal","default","delegate",
//"do",
"double",
//"else",
"enum",
//"event",
"explicit","extern",
"false","finally","fixed",
//"float","for",
"foreach",
"goto",
//"if",
"implicit","in","int","interface","internal","is",
"lock","long",
"namespace","new","null",
"object","operator","out","override",
"params","private","protected","public",
"readonly","ref",
//"return",
"sbyte","sealed","short","sizeof","stackalloc","static",
//"string",
"struct","switch",
"this","throw","true","try","typeof",
"uint","ulong","unchecked","unsafe","ushort","using",
"virtual","void","volatile",
//"while"
});
/// <summary>
/// Returns true if the passed string is in the list of reserved words with
/// a little simple pre-filtering.
/// </summary>
internal static bool IsReservedWord(string word)
{
// A couple of quick filters to weed out single characters, ll functions and
// anything that starts with an uppercase letter
if (String.IsNullOrEmpty(word)) return false;
if (word.Length < 2) return false;
if (word.StartsWith("ll")) return false;
char first = word.ToCharArray(0,1)[0];
if (first >= 'A' && first <= 'Z') return false;
return (reservedWords.BinarySearch(word) >= 0);
}
}
}

View File

@@ -1,852 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Text;
using Microsoft.CSharp;
//using Microsoft.JScript;
using Microsoft.VisualBasic;
using log4net;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class Compiler : ICompiler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
internal enum enumCompileType
{
lsl = 0,
cs = 1,
vb = 2
}
/// <summary>
/// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
/// </summary>
public int LinesToRemoveOnError = 3;
private enumCompileType DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
private bool m_insertCoopTerminationCalls;
private string FilePrefix;
private string ScriptEnginesPath = null;
// mapping between LSL and C# line/column numbers
private ICodeConverter LSL_Converter;
private List<string> m_warnings = new List<string>();
private static UInt64 scriptCompileCounter = 0; // And a counter
public IScriptEngine m_scriptEngine;
private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
public bool in_startup = true;
public Compiler(IScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ScriptEnginesPath = scriptEngine.ScriptEnginePath;
ReadConfig();
}
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
m_insertCoopTerminationCalls = m_scriptEngine.Config.GetString("ScriptStopStrategy", "abort") == "co-op";
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
if (in_startup)
{
in_startup = false;
CheckOrCreateScriptsDirectory();
// First time we start? Delete old files
if (DeleteScriptsOnStartup)
DeleteOldFiles();
}
// Map name and enum type of our supported languages
LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
#if DEBUG
m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
#endif
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
if (!LanguageMapping.ContainsKey(strlan))
{
m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
}
else
{
#if DEBUG
//m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
#endif
}
AllowedCompilers.Add(strlan, true);
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
// Default language
string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
// Is this language recognized at all?
if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
defaultCompileLanguage = "lsl";
}
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
else
{
#if DEBUG
// m_log.Debug("[Compiler]: " +
// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
#endif
// LANGUAGE IS IN ALLOW-LIST
DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
}
// We now have an allow-list, a mapping list, and a default language
}
/// <summary>
/// Create the directory where compiled scripts are stored if it does not already exist.
/// </summary>
private void CheckOrCreateScriptsDirectory()
{
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()));
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString());
}
}
}
/// <summary>
/// Delete old script files
/// </summary>
private void DeleteOldFiles()
{
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
}
public string GetCompilerOutput(string assetID)
{
return Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll"));
}
public string GetCompilerOutput(UUID assetID)
{
return GetCompilerOutput(assetID.ToString());
}
public void PerformScriptCompile(
string source, string asset, UUID ownerUUID,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
PerformScriptCompile(source, asset, ownerUUID, false, out assembly, out linemap);
}
public void PerformScriptCompile(
string source, string asset, UUID ownerUUID, bool alwaysRecompile,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
// m_log.DebugFormat("[Compiler]: Checking script for asset {0} in {1}\n{2}", asset, m_scriptEngine.World.Name, source);
IScriptModuleComms comms = m_scriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
linemap = null;
m_warnings.Clear();
assembly = GetCompilerOutput(asset);
// m_log.DebugFormat("[Compiler]: Retrieved assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
CheckOrCreateScriptsDirectory();
// Don't recompile if we're not forced to and we already have it
// Performing 3 file exists tests for every script can still be slow
if (!alwaysRecompile && File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
{
// m_log.DebugFormat("[Compiler]: Found existing assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
// If we have already read this linemap file, then it will be in our dictionary.
// Don't build another copy of the dictionary (saves memory) and certainly
// don't keep reading the same file from disk multiple times.
if (!m_lineMaps.ContainsKey(assembly))
m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
linemap = m_lineMaps[assembly];
return;
}
// m_log.DebugFormat("[Compiler]: Compiling assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
if (source.Length == 0)
throw new Exception("Cannot find script assembly and no script text present");
enumCompileType language = DefaultCompileLanguage;
if (source.StartsWith("//c#", true, CultureInfo.InvariantCulture))
language = enumCompileType.cs;
if (source.StartsWith("//vb", true, CultureInfo.InvariantCulture))
{
language = enumCompileType.vb;
// We need to remove //vb, it won't compile with that
source = source.Substring(4, source.Length - 4);
}
if (source.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
language = enumCompileType.lsl;
// m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
if (!AllowedCompilers.ContainsKey(language.ToString()))
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
throw new Exception(errtext);
}
if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
throw new Exception(errtext);
}
string compileScript = string.Empty;
if (language == enumCompileType.lsl)
{
// Its LSL, convert it to C#
StringBuilder sb = new StringBuilder(16394);
LSL_Converter = (ICodeConverter)new CSCodeGenerator(comms, m_insertCoopTerminationCalls);
AddCSScriptHeader(
m_scriptEngine.ScriptClassName,
m_scriptEngine.ScriptBaseClassName,
m_scriptEngine.ScriptBaseClassParameters,
sb);
LSL_Converter.Convert(source,sb);
AddCSScriptTail(sb);
compileScript = sb.ToString();
// copy converter warnings into our warnings.
foreach (string warning in LSL_Converter.GetWarnings())
{
AddWarning(warning);
}
linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
// Write the linemap to a file and save it in our dictionary for next time.
m_lineMaps[assembly] = linemap;
WriteMapFile(assembly + ".map", linemap);
LSL_Converter.Clear();
}
else
{
switch (language)
{
case enumCompileType.cs:
compileScript = CreateCSCompilerScript(
source,
m_scriptEngine.ScriptClassName,
m_scriptEngine.ScriptBaseClassName,
m_scriptEngine.ScriptBaseClassParameters);
break;
case enumCompileType.vb:
compileScript = CreateVBCompilerScript(
source, m_scriptEngine.ScriptClassName, m_scriptEngine.ScriptBaseClassName);
break;
}
}
assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
// private static string CreateJSCompilerScript(string compileScript)
// {
// compileScript = String.Empty +
// "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
// "package SecondLife {\r\n" +
// "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
// compileScript +
// "} }\r\n";
// return compileScript;
// }
public static void AddCSScriptHeader(string className, string baseClassName, ParameterInfo[] constructorParameters, StringBuilder sb)
{
sb.Append(string.Format(
@"using OpenSim.Region.ScriptEngine.Shared;
using System.Collections.Generic;
namespace SecondLife
{{
public class {0} : {1}
{{
public {0}({2}) : base({3}) {{}}
",
className,
baseClassName,
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
: "",
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
: ""
));
}
public static void AddCSScriptTail(StringBuilder sb)
{
sb.Append(string.Format(" }}\n}}\n"));
}
public static string CreateCSCompilerScript(
string compileScript, string className, string baseClassName, ParameterInfo[] constructorParameters)
{
compileScript = string.Format(
@"using OpenSim.Region.ScriptEngine.Shared;
using System.Collections.Generic;
namespace SecondLife
{{
public class {0} : {1}
{{
public {0}({2}) : base({3}) {{}}
{4}
}}
}}",
className,
baseClassName,
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
: "",
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
: "",
compileScript);
return compileScript;
}
public static string CreateVBCompilerScript(string compileScript, string className, string baseClassName)
{
compileScript = String.Empty +
"Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
String.Empty + "NameSpace SecondLife:" +
String.Empty + "Public Class " + className + ": Inherits " + baseClassName +
"\r\nPublic Sub New()\r\nEnd Sub: " +
compileScript +
":End Class :End Namespace\r\n";
return compileScript;
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
{
// m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
string ext = "." + lang.ToString();
// Output assembly name
scriptCompileCounter++;
try
{
if (File.Exists(assembly))
{
File.SetAttributes(assembly, FileAttributes.Normal);
File.Delete(assembly);
}
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing " +
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(Path.Combine(
ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
if (m_scriptEngine.ScriptReferencedAssemblies != null)
Array.ForEach<string>(
m_scriptEngine.ScriptReferencedAssemblies,
a => parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, a)));
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assembly;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
parameters.GenerateInMemory = false;
// parameters.TempFiles = new TempFileCollection(Path.Combine(ScriptEnginesPath,
// m_scriptEngine.World.RegionInfo.RegionID.ToString()), CompileWithDebugInformation);
CompilerResults results;
CodeDomProvider provider;
switch (lang)
{
case enumCompileType.vb:
provider = CodeDomProvider.CreateProvider("VisualBasic");
break;
case enumCompileType.cs:
case enumCompileType.lsl:
provider = CodeDomProvider.CreateProvider("CSharp");
break;
default:
throw new Exception("Compiler is not able to recongnize " +
"language type \"" + lang.ToString() + "\"");
}
if(provider == null)
throw new Exception("Compiler failed to load ");
bool complete = false;
bool retried = false;
do
{
results = provider.CompileAssemblyFromSource(
parameters, Script);
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
//
// WARNINGS AND ERRORS
//
bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> errorPos;
// Show 5 errors max, but check entire list for errors
if (severity == "Error")
{
// C# scripts will not have a linemap since theres no line translation involved.
if (!m_lineMaps.ContainsKey(assembly))
errorPos = new KeyValuePair<int, int>(CompErr.Line, CompErr.Column);
else
errorPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
string text = CompErr.ErrorText;
// Use LSL type names
if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
errorPos.Key - 1, errorPos.Value - 1,
CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
}
}
provider.Dispose();
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(assembly))
{
for (int i = 0; i < 20 && !File.Exists(assembly); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(assembly))
{
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset);
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(assembly);
if (fi == null)
{
errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
using (FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read))
fs.Read(data, 0, data.Length);
}
catch (Exception)
{
errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
Byte[] buf = Encoding.ASCII.GetBytes(filetext);
using (FileStream sfs = File.Create(assembly + ".text"))
sfs.Write(buf, 0, buf.Length);
return assembly;
}
private class kvpSorter : IComparer<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>
{
public int Compare(KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> a,
KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> b)
{
int kc = a.Key.Key.CompareTo(b.Key.Key);
return (kc != 0) ? kc : a.Key.Value.CompareTo(b.Key.Value);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
var sorted = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>(positionMap);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
int pl = 1;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> posmap in sorted)
{
//m_log.DebugFormat("[Compiler]: Scanning line map {0},{1} --> {2},{3}", posmap.Key.Key, posmap.Key.Value, posmap.Value.Key, posmap.Value.Value);
int nl = posmap.Value.Key + line - posmap.Key.Key; // New, translated LSL line and column.
int nc = posmap.Value.Value + col - posmap.Key.Value;
// Keep going until we find the first point passed line,col.
if (posmap.Key.Key > line)
{
//m_log.DebugFormat("[Compiler]: Line is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
if (pl < line)
{
//m_log.DebugFormat("[Compiler]: Previous line ({0}) is less than requested line ({1}), setting column to 1.", pl, line);
c = 1;
}
break;
}
if (posmap.Key.Key == line && posmap.Key.Value > col)
{
// Never move l,c backwards.
if (nl > l || (nl == l && nc > c))
{
//m_log.DebugFormat("[Compiler]: Using offset relative to this: {0} + {1} - {2}, {3} + {4} - {5} = {6}, {7}",
// posmap.Value.Key, line, posmap.Key.Key, posmap.Value.Value, col, posmap.Key.Value, nl, nc);
l = nl;
c = nc;
}
//m_log.DebugFormat("[Compiler]: Column is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
break;
}
pl = posmap.Key.Key;
l = posmap.Value.Key;
c = posmap.Value.Value;
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
StringBuilder mapbuilder = new StringBuilder(1024);
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
{
KeyValuePair<int, int> k = kvp.Key;
KeyValuePair<int, int> v = kvp.Value;
mapbuilder.Append(String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value));
}
Byte[] mapbytes = Encoding.ASCII.GetBytes(mapbuilder.ToString());
using (FileStream mfs = File.Create(filename))
mfs.Write(mapbytes, 0, mapbytes.Length);
}
private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
{
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
try
{
using (StreamReader r = File.OpenText(filename))
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
string line;
while ((line = r.ReadLine()) != null)
{
String[] parts = line.Split(new Char[] { ',' });
int kk = System.Convert.ToInt32(parts[0]);
int kv = System.Convert.ToInt32(parts[1]);
int vk = System.Convert.ToInt32(parts[2]);
int vv = System.Convert.ToInt32(parts[3]);
KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
linemap[k] = v;
}
}
}
catch
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
}
return linemap;
}
}
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using System.Text;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public interface ICodeConverter
{
string Convert(string script);
void Convert(string script, StringBuilder sb);
string[] GetWarnings();
void Clear();
}
}

View File

@@ -1,205 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Tools;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class LSL2CSCodeTransformer
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SYMBOL m_astRoot = null;
private static Dictionary<string, string> m_datatypeLSL2OpenSim = null;
/// <summary>
/// Pass the new CodeTranformer an abstract syntax tree.
/// </summary>
/// <param name="astRoot">The root node of the AST.</param>
public LSL2CSCodeTransformer(SYMBOL astRoot)
{
m_astRoot = astRoot;
// let's populate the dictionary
if (null == m_datatypeLSL2OpenSim)
{
m_datatypeLSL2OpenSim = new Dictionary<string, string>();
m_datatypeLSL2OpenSim.Add("integer", "LSL_Types.LSLInteger");
m_datatypeLSL2OpenSim.Add("float", "LSL_Types.LSLFloat");
//m_datatypeLSL2OpenSim.Add("key", "LSL_Types.key"); // key doesn't seem to be used
m_datatypeLSL2OpenSim.Add("key", "LSL_Types.LSLString");
m_datatypeLSL2OpenSim.Add("string", "LSL_Types.LSLString");
m_datatypeLSL2OpenSim.Add("vector", "LSL_Types.Vector3");
m_datatypeLSL2OpenSim.Add("rotation", "LSL_Types.Quaternion");
m_datatypeLSL2OpenSim.Add("list", "LSL_Types.list");
}
}
/// <summary>
/// Transform the code in the AST we have.
/// </summary>
/// <returns>The root node of the transformed AST</returns>
public SYMBOL Transform()
{
foreach (SYMBOL s in m_astRoot.kids)
TransformNode(s);
return m_astRoot;
}
/// <summary>
/// Recursively called to transform each type of node. Will transform this
/// node, then all it's children.
/// </summary>
/// <param name="s">The current node to transform.</param>
private void TransformNode(SYMBOL s)
{
// m_log.DebugFormat("[LSL2CSCODETRANSFORMER]: Tranforming node {0}", s);
// make sure to put type lower in the inheritance hierarchy first
// ie: since IdentConstant and StringConstant inherit from Constant,
// put IdentConstant and StringConstant before Constant
if (s is Declaration)
((Declaration) s).Datatype = m_datatypeLSL2OpenSim[((Declaration) s).Datatype];
else if (s is Constant)
((Constant) s).Type = m_datatypeLSL2OpenSim[((Constant) s).Type];
else if (s is TypecastExpression)
((TypecastExpression) s).TypecastType = m_datatypeLSL2OpenSim[((TypecastExpression) s).TypecastType];
else if (s is GlobalFunctionDefinition && "void" != ((GlobalFunctionDefinition) s).ReturnType) // we don't need to translate "void"
((GlobalFunctionDefinition) s).ReturnType = m_datatypeLSL2OpenSim[((GlobalFunctionDefinition) s).ReturnType];
for (int i = 0; i < s.kids.Count; i++)
{
// It's possible that a child is null, for instance when the
// assignment part in a for-loop is left out, ie:
//
// for (; i < 10; i++)
// {
// ...
// }
//
// We need to check for that here.
if (null != s.kids[i])
{
// m_log.Debug("[LSL2CSCODETRANSFORMER]: Moving down level");
if (!(s is Assignment || s is ArgumentDeclarationList) && s.kids[i] is Declaration)
AddImplicitInitialization(s, i);
TransformNode((SYMBOL) s.kids[i]);
// m_log.Debug("[LSL2CSCODETRANSFORMER]: Moving up level");
}
}
}
/// <summary>
/// Replaces an instance of the node at s.kids[didx] with an assignment
/// node. The assignment node has the Declaration node on the left hand
/// side and a default initializer on the right hand side.
/// </summary>
/// <param name="s">
/// The node containing the Declaration node that needs replacing.
/// </param>
/// <param name="didx">Index of the Declaration node to replace.</param>
private void AddImplicitInitialization(SYMBOL s, int didx)
{
// We take the kids for a while to play with them.
int sKidSize = s.kids.Count;
object [] sKids = new object[sKidSize];
for (int i = 0; i < sKidSize; i++)
sKids[i] = s.kids.Pop();
// The child to be changed.
Declaration currentDeclaration = (Declaration) sKids[didx];
// We need an assignment node.
Assignment newAssignment = new Assignment(currentDeclaration.yyps,
currentDeclaration,
GetZeroConstant(currentDeclaration.yyps, currentDeclaration.Datatype),
"=");
sKids[didx] = newAssignment;
// Put the kids back where they belong.
for (int i = 0; i < sKidSize; i++)
s.kids.Add(sKids[i]);
}
/// <summary>
/// Generates the node structure required to generate a default
/// initialization.
/// </summary>
/// <param name="p">
/// Tools.Parser instance to use when instantiating nodes.
/// </param>
/// <param name="constantType">String describing the datatype.</param>
/// <returns>
/// A SYMBOL node conaining the appropriate structure for intializing a
/// constantType.
/// </returns>
private SYMBOL GetZeroConstant(Parser p, string constantType)
{
switch (constantType)
{
case "integer":
return new Constant(p, constantType, "0");
case "float":
return new Constant(p, constantType, "0.0");
case "string":
case "key":
return new Constant(p, constantType, "");
case "list":
ArgumentList al = new ArgumentList(p);
return new ListConstant(p, al);
case "vector":
Constant vca = new Constant(p, "float", "0.0");
Constant vcb = new Constant(p, "float", "0.0");
Constant vcc = new Constant(p, "float", "0.0");
ConstantExpression vcea = new ConstantExpression(p, vca);
ConstantExpression vceb = new ConstantExpression(p, vcb);
ConstantExpression vcec = new ConstantExpression(p, vcc);
return new VectorConstant(p, vcea, vceb, vcec);
case "rotation":
Constant rca = new Constant(p, "float", "0.0");
Constant rcb = new Constant(p, "float", "0.0");
Constant rcc = new Constant(p, "float", "0.0");
Constant rcd = new Constant(p, "float", "1.0");
ConstantExpression rcea = new ConstantExpression(p, rca);
ConstantExpression rceb = new ConstantExpression(p, rcb);
ConstantExpression rcec = new ConstantExpression(p, rcc);
ConstantExpression rced = new ConstantExpression(p, rcd);
return new RotationConstant(p, rcea, rceb, rcec, rced);
default:
return null; // this will probably break stuff
}
}
}
}

View File

@@ -1,33 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OpenSim.Region.ScriptEngine.Shared.CodeTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("http://opensimulator.org")]
[assembly: AssemblyProduct("OpenSim")]
[assembly: AssemblyCopyright("OpenSimulator developers")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd446fb3-3a21-471b-951c-68b9eb6ef8e5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion(OpenSim.VersionInfo.AssemblyVersionNumber)]

View File

@@ -1,217 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.CSharp;
using NUnit.Framework;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools.Tests
{
/// <summary>
/// Tests the LSL compiler. Among other things, test that error messages
/// generated by the C# compiler can be mapped to prper lines/columns in
/// the LSL source.
/// </summary>
[TestFixture]
public class CompilerTest : OpenSimTestCase
{
private string m_testDir;
private CSharpCodeProvider m_CSCodeProvider;
private CompilerParameters m_compilerParameters;
// private CompilerResults m_compilerResults;
private ResolveEventHandler m_resolveEventHandler;
/// <summary>
/// Creates a temporary directory where build artifacts are stored.
/// </summary>
[TestFixtureSetUp]
public void Init()
{
m_testDir = Path.Combine(Path.GetTempPath(), "opensim_compilerTest_" + Path.GetRandomFileName());
if (!Directory.Exists(m_testDir))
{
// Create the temporary directory for housing build artifacts.
Directory.CreateDirectory(m_testDir);
}
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// Create a CSCodeProvider and CompilerParameters.
m_CSCodeProvider = new CSharpCodeProvider();
m_compilerParameters = new CompilerParameters();
string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
m_resolveEventHandler = new ResolveEventHandler(AssemblyResolver.OnAssemblyResolve);
System.AppDomain.CurrentDomain.AssemblyResolve += m_resolveEventHandler;
m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll"));
m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenMetaverseTypes.dll"));
m_compilerParameters.GenerateExecutable = false;
}
/// <summary>
/// Removes the temporary build directory and any build artifacts
/// inside it.
/// </summary>
[TearDown]
public void CleanUp()
{
System.AppDomain.CurrentDomain.AssemblyResolve -= m_resolveEventHandler;
if (Directory.Exists(m_testDir))
{
// Blow away the temporary directory with artifacts.
Directory.Delete(m_testDir, true);
}
}
private CompilerResults CompileScript(
string input, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap)
{
m_compilerParameters.OutputAssembly = Path.Combine(m_testDir, Path.GetRandomFileName() + ".dll");
CSCodeGenerator cg = new CSCodeGenerator();
string output = cg.Convert(input);
output = Compiler.CreateCSCompilerScript(output, "script1", typeof(ScriptBaseClass).FullName, null);
// System.Console.WriteLine(output);
positionMap = cg.PositionMap;
CompilerResults compilerResults = m_CSCodeProvider.CompileAssemblyFromSource(m_compilerParameters, output);
// foreach (KeyValuePair<int, int> key in positionMap.Keys)
// {
// KeyValuePair<int, int> val = positionMap[key];
//
// System.Console.WriteLine("{0},{1} => {2},{3}", key.Key, key.Value, val.Key, val.Value);
// }
//
// foreach (CompilerError compErr in m_compilerResults.Errors)
// {
// System.Console.WriteLine("Error: {0},{1} => {2}", compErr.Line, compErr.Column, compErr);
// }
return compilerResults;
}
/* test too depedent on counting lines and columns maping code generation changes
erros position is better tested on viewers
/// <summary>
/// Test that line number errors are resolved as expected when preceding code contains a jump.
/// </summary>
[Test]
public void TestJumpAndSyntaxError()
{
TestHelpers.InMethod();
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap;
CompilerResults compilerResults = CompileScript(
@"default
{
state_entry()
{
jump l;
@l;
i = 1;
}
}", out positionMap);
Assert.AreEqual(
new KeyValuePair<int, int>(7, 9),
positionMap[new KeyValuePair<int, int>(compilerResults.Errors[0].Line, compilerResults.Errors[0].Column)]);
}
/// <summary>
/// Test the C# compiler error message can be mapped to the correct
/// line/column in the LSL source when an undeclared variable is used.
/// </summary>
[Test]
public void TestUseUndeclaredVariable()
{
TestHelpers.InMethod();
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap;
CompilerResults compilerResults = CompileScript(
@"default
{
state_entry()
{
integer y = x + 3;
}
}", out positionMap);
Assert.AreEqual(
new KeyValuePair<int, int>(5, 21),
positionMap[new KeyValuePair<int, int>(compilerResults.Errors[0].Line, compilerResults.Errors[0].Column)]);
}
*/
/// <summary>
/// Test that a string can be cast to string and another string
/// concatenated.
/// </summary>
[Test]
public void TestCastAndConcatString()
{
TestHelpers.InMethod();
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap;
CompilerResults compilerResults = CompileScript(
@"string s = "" a string"";
default
{
state_entry()
{
key gAvatarKey = llDetectedKey(0);
string tmp = (string) gAvatarKey + s;
llSay(0, tmp);
}
}", out positionMap);
Assert.AreEqual(0, compilerResults.Errors.Count);
}
}
}

View File

@@ -1,359 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
public class LSL_EventTests : OpenSimTestCase
{
CSCodeGenerator m_cg = new CSCodeGenerator();
[Test]
public void TestBadEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestCompile("default { bad() {} }", true);
}
[Test]
public void TestAttachEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestKeyArgEvent("attach");
}
[Test]
public void TestObjectRezEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestKeyArgEvent("object_rez");
}
[Test]
public void TestMovingEndEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("moving_end");
}
[Test]
public void TestMovingStartEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("moving_start");
}
[Test]
public void TestNoSensorEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("no_sensor");
}
[Test]
public void TestNotAtRotTargetEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("not_at_rot_target");
}
[Test]
public void TestNotAtTargetEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("not_at_target");
}
[Test]
public void TestStateEntryEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("state_entry");
}
[Test]
public void TestStateExitEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("state_exit");
}
[Test]
public void TestTimerEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVoidArgEvent("timer");
}
private void TestVoidArgEvent(string eventName)
{
TestCompile("default { " + eventName + "() {} }", false);
TestCompile("default { " + eventName + "(integer n) {} }", true);
}
[Test]
public void TestChangedEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("changed");
}
[Test]
public void TestCollisionEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("collision");
}
[Test]
public void TestCollisionStartEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("collision_start");
}
[Test]
public void TestCollisionEndEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("collision_end");
}
[Test]
public void TestOnRezEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("on_rez");
}
[Test]
public void TestRunTimePermissionsEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("run_time_permissions");
}
[Test]
public void TestSensorEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("sensor");
}
[Test]
public void TestTouchEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("touch");
}
[Test]
public void TestTouchStartEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("touch_start");
}
[Test]
public void TestTouchEndEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntArgEvent("touch_end");
}
[Test]
public void TestLandCollisionEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVectorArgEvent("land_collision");
}
[Test]
public void TestLandCollisionStartEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVectorArgEvent("land_collision_start");
}
[Test]
public void TestLandCollisionEndEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestVectorArgEvent("land_collision_end");
}
[Test]
public void TestAtRotTargetEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntRotRotArgEvent("at_rot_target");
}
[Test]
public void TestAtTargetEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestIntVecVecArgEvent("at_target");
}
[Test]
public void TestControlEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestKeyIntIntArgEvent("control");
}
private void TestIntArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(integer n) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(integer n, integer o) {{}} }", true);
}
private void TestKeyArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(key k) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(key k, key l) {{}} }", true);
}
private void TestVectorArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(vector v) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(vector v, vector w) {{}} }", true);
}
private void TestIntRotRotArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(integer n, rotation r, rotation s) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(integer n, rotation r, rotation s, rotation t) {{}} }", true);
}
private void TestIntVecVecArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(integer n, vector v, vector w) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(integer n, vector v, vector w, vector x) {{}} }", true);
}
private void TestKeyIntIntArgEvent(string eventName)
{
TestCompile("default { " + eventName + "(key k, integer n, integer o) {} }", false);
TestCompile("default { " + eventName + "{{}} }", true);
TestCompile("default { " + eventName + "(string s) {{}} }", true);
TestCompile("default { " + eventName + "(key k, integer n, integer o, integer p) {{}} }", true);
}
private void TestCompile(string script, bool expectException)
{
bool gotException = false;
Exception ge = null;
try
{
m_cg.Convert(script);
}
catch (Exception e)
{
gotException = true;
ge = e;
}
Assert.That(
gotException,
Is.EqualTo(expectException),
"Failed on {0}, exception {1}", script, ge != null ? ge.ToString() : "n/a");
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,496 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.Instance
{
public class ScriptSerializer
{
public static string Serialize(ScriptInstance instance)
{
bool running = instance.Running;
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ScriptState",
"");
xmldoc.AppendChild(rootElement);
XmlElement state = xmldoc.CreateElement("", "State", "");
state.AppendChild(xmldoc.CreateTextNode(instance.State));
rootElement.AppendChild(state);
XmlElement run = xmldoc.CreateElement("", "Running", "");
run.AppendChild(xmldoc.CreateTextNode(
running.ToString()));
rootElement.AppendChild(run);
Dictionary<string, Object> vars = instance.GetVars();
XmlElement variables = xmldoc.CreateElement("", "Variables", "");
foreach (KeyValuePair<string, Object> var in vars)
WriteTypedValue(xmldoc, variables, "Variable", var.Key,
var.Value);
rootElement.AppendChild(variables);
XmlElement queue = xmldoc.CreateElement("", "Queue", "");
int count = instance.EventQueue.Count;
while (count > 0)
{
EventParams ep = (EventParams)instance.EventQueue.Dequeue();
instance.EventQueue.Enqueue(ep);
count--;
XmlElement item = xmldoc.CreateElement("", "Item", "");
XmlAttribute itemEvent = xmldoc.CreateAttribute("", "event",
"");
itemEvent.Value = ep.EventName;
item.Attributes.Append(itemEvent);
XmlElement parms = xmldoc.CreateElement("", "Params", "");
foreach (Object o in ep.Params)
WriteTypedValue(xmldoc, parms, "Param", String.Empty, o);
item.AppendChild(parms);
XmlElement detect = xmldoc.CreateElement("", "Detected", "");
foreach (DetectParams det in ep.DetectParams)
{
XmlElement objectElem = xmldoc.CreateElement("", "Object", "");
XmlAttribute pos = xmldoc.CreateAttribute("", "pos", "");
pos.Value = det.OffsetPos.ToString();
objectElem.Attributes.Append(pos);
XmlAttribute d_linkNum = xmldoc.CreateAttribute("", "linkNum", "");
d_linkNum.Value = det.LinkNum.ToString();
objectElem.Attributes.Append(d_linkNum);
XmlAttribute d_group = xmldoc.CreateAttribute("", "group", "");
d_group.Value = det.Group.ToString();
objectElem.Attributes.Append(d_group);
XmlAttribute d_name = xmldoc.CreateAttribute("", "name", "");
d_name.Value = det.Name.ToString();
objectElem.Attributes.Append(d_name);
XmlAttribute d_owner = xmldoc.CreateAttribute("", "owner", "");
d_owner.Value = det.Owner.ToString();
objectElem.Attributes.Append(d_owner);
XmlAttribute d_position = xmldoc.CreateAttribute("", "position", "");
d_position.Value = det.Position.ToString();
objectElem.Attributes.Append(d_position);
XmlAttribute d_rotation = xmldoc.CreateAttribute("", "rotation", "");
d_rotation.Value = det.Rotation.ToString();
objectElem.Attributes.Append(d_rotation);
XmlAttribute d_type = xmldoc.CreateAttribute("", "type", "");
d_type.Value = det.Type.ToString();
objectElem.Attributes.Append(d_type);
XmlAttribute d_velocity = xmldoc.CreateAttribute("", "velocity", "");
d_velocity.Value = det.Velocity.ToString();
objectElem.Attributes.Append(d_velocity);
objectElem.AppendChild(
xmldoc.CreateTextNode(det.Key.ToString()));
detect.AppendChild(objectElem);
}
item.AppendChild(detect);
queue.AppendChild(item);
}
rootElement.AppendChild(queue);
XmlNode plugins = xmldoc.CreateElement("", "Plugins", "");
DumpList(xmldoc, plugins,
new LSL_Types.list(instance.PluginData));
rootElement.AppendChild(plugins);
if (instance.ScriptTask != null)
{
if (instance.ScriptTask.PermsMask != 0 && !instance.ScriptTask.PermsGranter.IsZero())
{
XmlNode permissions = xmldoc.CreateElement("", "Permissions", "");
XmlAttribute granter = xmldoc.CreateAttribute("", "granter", "");
granter.Value = instance.ScriptTask.PermsGranter.ToString();
permissions.Attributes.Append(granter);
XmlAttribute mask = xmldoc.CreateAttribute("", "mask", "");
mask.Value = instance.ScriptTask.PermsMask.ToString();
permissions.Attributes.Append(mask);
rootElement.AppendChild(permissions);
}
}
if (instance.MinEventDelay > 0.0)
{
XmlElement eventDelay = xmldoc.CreateElement("", "MinEventDelay", "");
eventDelay.AppendChild(xmldoc.CreateTextNode(instance.MinEventDelay.ToString()));
rootElement.AppendChild(eventDelay);
}
return xmldoc.InnerXml;
}
public static void Deserialize(string xml, ScriptInstance instance)
{
XmlDocument doc = new XmlDocument();
Dictionary<string, object> vars = instance.GetVars();
instance.PluginData = new Object[0];
doc.LoadXml(xml);
XmlNodeList rootL = doc.GetElementsByTagName("ScriptState");
if (rootL.Count != 1)
{
return;
}
XmlNode rootNode = rootL[0];
if (rootNode != null)
{
object varValue;
XmlNodeList partL = rootNode.ChildNodes;
foreach (XmlNode part in partL)
{
switch (part.Name)
{
case "State":
instance.State=part.InnerText;
break;
case "Running":
instance.Running = bool.Parse(part.InnerText);
break;
case "Variables":
XmlNodeList varL = part.ChildNodes;
foreach (XmlNode var in varL)
{
string varName;
varValue=ReadTypedValue(var, out varName);
if (vars.ContainsKey(varName))
vars[varName] = varValue;
}
instance.SetVars(vars);
break;
case "Queue":
XmlNodeList itemL = part.ChildNodes;
foreach (XmlNode item in itemL)
{
List<Object> parms = new List<Object>();
List<DetectParams> detected =
new List<DetectParams>();
string eventName =
item.Attributes.GetNamedItem("event").Value;
XmlNodeList eventL = item.ChildNodes;
foreach (XmlNode evt in eventL)
{
switch (evt.Name)
{
case "Params":
XmlNodeList prms = evt.ChildNodes;
foreach (XmlNode pm in prms)
parms.Add(ReadTypedValue(pm));
break;
case "Detected":
XmlNodeList detL = evt.ChildNodes;
foreach (XmlNode det in detL)
{
string vect =
det.Attributes.GetNamedItem(
"pos").Value;
LSL_Types.Vector3 v =
new LSL_Types.Vector3(vect);
int d_linkNum=0;
UUID d_group = UUID.Zero;
string d_name = String.Empty;
UUID d_owner = UUID.Zero;
LSL_Types.Vector3 d_position =
new LSL_Types.Vector3();
LSL_Types.Quaternion d_rotation =
new LSL_Types.Quaternion();
int d_type = 0;
LSL_Types.Vector3 d_velocity =
new LSL_Types.Vector3();
try
{
string tmp;
tmp = det.Attributes.GetNamedItem(
"linkNum").Value;
int.TryParse(tmp, out d_linkNum);
tmp = det.Attributes.GetNamedItem(
"group").Value;
UUID.TryParse(tmp, out d_group);
d_name = det.Attributes.GetNamedItem(
"name").Value;
tmp = det.Attributes.GetNamedItem(
"owner").Value;
UUID.TryParse(tmp, out d_owner);
tmp = det.Attributes.GetNamedItem(
"position").Value;
d_position =
new LSL_Types.Vector3(tmp);
tmp = det.Attributes.GetNamedItem(
"rotation").Value;
d_rotation =
new LSL_Types.Quaternion(tmp);
tmp = det.Attributes.GetNamedItem(
"type").Value;
int.TryParse(tmp, out d_type);
tmp = det.Attributes.GetNamedItem(
"velocity").Value;
d_velocity =
new LSL_Types.Vector3(tmp);
}
catch (Exception) // Old version XML
{
}
UUID uuid = new UUID();
UUID.TryParse(det.InnerText,
out uuid);
DetectParams d = new DetectParams();
d.Key = uuid;
d.OffsetPos = v;
d.LinkNum = d_linkNum;
d.Group = d_group;
d.Name = d_name;
d.Owner = d_owner;
d.Position = d_position;
d.Rotation = d_rotation;
d.Type = d_type;
d.Velocity = d_velocity;
detected.Add(d);
}
break;
}
}
EventParams ep = new EventParams(
eventName, parms.ToArray(),
detected.ToArray());
instance.EventQueue.Enqueue(ep);
}
break;
case "Plugins":
instance.PluginData = ReadList(part).Data;
break;
case "Permissions":
string tmpPerm;
int mask = 0;
tmpPerm = part.Attributes.GetNamedItem("mask").Value;
if (tmpPerm != null)
{
int.TryParse(tmpPerm, out mask);
if (mask != 0)
{
tmpPerm = part.Attributes.GetNamedItem("granter").Value;
if (tmpPerm != null)
{
UUID granter = new UUID();
UUID.TryParse(tmpPerm, out granter);
if (!granter.IsZero())
{
instance.ScriptTask.PermsMask = mask;
instance.ScriptTask.PermsGranter = granter;
}
}
}
}
break;
case "MinEventDelay":
double minEventDelay = 0.0;
double.TryParse(part.InnerText, NumberStyles.Float, Culture.NumberFormatInfo, out minEventDelay);
instance.MinEventDelay = minEventDelay;
break;
}
}
}
}
private static void DumpList(XmlDocument doc, XmlNode parent,
LSL_Types.list l)
{
foreach (Object o in l.Data)
WriteTypedValue(doc, parent, "ListItem", "", o);
}
private static LSL_Types.list ReadList(XmlNode parent)
{
List<Object> olist = new List<Object>();
XmlNodeList itemL = parent.ChildNodes;
foreach (XmlNode item in itemL)
olist.Add(ReadTypedValue(item));
return new LSL_Types.list(olist.ToArray());
}
private static void WriteTypedValue(XmlDocument doc, XmlNode parent,
string tag, string name, object value)
{
Type t=value.GetType();
XmlAttribute typ = doc.CreateAttribute("", "type", "");
XmlNode n = doc.CreateElement("", tag, "");
if (value is LSL_Types.list)
{
typ.Value = "list";
n.Attributes.Append(typ);
DumpList(doc, n, (LSL_Types.list) value);
if (name != String.Empty)
{
XmlAttribute nam = doc.CreateAttribute("", "name", "");
nam.Value = name;
n.Attributes.Append(nam);
}
parent.AppendChild(n);
return;
}
n.AppendChild(doc.CreateTextNode(value.ToString()));
typ.Value = t.ToString();
n.Attributes.Append(typ);
if (name != String.Empty)
{
XmlAttribute nam = doc.CreateAttribute("", "name", "");
nam.Value = name;
n.Attributes.Append(nam);
}
parent.AppendChild(n);
}
private static object ReadTypedValue(XmlNode tag, out string name)
{
name = tag.Attributes.GetNamedItem("name").Value;
return ReadTypedValue(tag);
}
private static object ReadTypedValue(XmlNode tag)
{
Object varValue;
string assembly;
string itemType = tag.Attributes.GetNamedItem("type").Value;
if (itemType == "list")
return ReadList(tag);
if (itemType == "OpenMetaverse.UUID")
{
UUID val = new UUID();
UUID.TryParse(tag.InnerText, out val);
return val;
}
Type itemT = Type.GetType(itemType);
if (itemT == null)
{
Object[] args =
new Object[] { tag.InnerText };
assembly = itemType+", OpenSim.Region.ScriptEngine.Shared";
itemT = Type.GetType(assembly);
if (itemT == null)
return null;
varValue = Activator.CreateInstance(itemT, args);
if (varValue == null)
return null;
}
else
{
varValue = Convert.ChangeType(tag.InnerText, itemT);
}
return varValue;
}
}
}

View File

@@ -41,7 +41,6 @@ using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
@@ -56,8 +55,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
[TestFixture]
public class LSL_ApiAvatarTests : OpenSimTestCase
{
/*
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
@@ -76,7 +75,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, initConfigSource);
m_engine = new XEngine.XEngine();
m_engine = new YEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
@@ -159,7 +158,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
m_scene.Update(1);
Assert.That(entityUpdates, Is.EqualTo(4));
}
*/
}
*/
}
}

View File

@@ -42,7 +42,6 @@ using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.World.Permissions;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using PermissionMask = OpenSim.Framework.PermissionMask;
@@ -53,6 +52,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
/// Tests for inventory functions in LSL
/// </summary>
[TestFixture]
/*
public class LSL_ApiInventoryTests : OpenSimTestCase
{
protected Scene m_scene;
@@ -296,4 +296,5 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
Assert.IsNull(otherOwnedTargetSo.RootPart.Inventory.GetInventoryItem("script"));
}
}
*/
}

View File

@@ -41,7 +41,6 @@ using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
@@ -58,6 +57,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
[TestFixture]
public class LSL_ApiLinkingTests : OpenSimTestCase
{
/*
protected Scene m_scene;
protected XEngine.XEngine m_engine;
@@ -99,7 +99,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
= TaskInventoryHelpers.AddNotecard(
m_scene.AssetService, grp1.RootPart, "ncItem", TestHelpers.ParseTail(0x800), TestHelpers.ParseTail(0x900), "Hello World!");
grp1Item.PermsMask |= ScriptBaseClass.PERMISSION_CHANGE_LINKS;
grp1Item.PermsGranter = ownerId;
SceneObjectGroup grp2 = SceneHelpers.CreateSceneObject(2, ownerId, "grp2-", 0x20);
grp2.AbsolutePosition = new Vector3(20, 20, 20);
@@ -189,4 +188,5 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
}
}
}
*/
}

View File

@@ -34,7 +34,6 @@ using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.Framework.Scenes;
using Nini.Config;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenMetaverse;

View File

@@ -41,7 +41,6 @@ using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
@@ -53,6 +52,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
[TestFixture]
public class LSL_ApiObjectTests : OpenSimTestCase
{
/*
private const double VECTOR_COMPONENT_ACCURACY = 0.0000005d;
private const float FLOAT_ACCURACY = 0.00005f;
@@ -395,4 +395,5 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
}
}
*/
}

View File

@@ -33,7 +33,6 @@ using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.Framework.Scenes;
using Nini.Config;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenMetaverse;
using System;

View File

@@ -41,7 +41,6 @@ using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
@@ -53,6 +52,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
[TestFixture]
public class OSSL_ApiAppearanceTest : OpenSimTestCase
{
/*
protected Scene m_scene;
protected XEngine.XEngine m_engine;
@@ -163,4 +163,5 @@ namespace OpenSim.Region.ScriptEngine.Shared.Tests
Assert.That(savedAppearance.AvatarHeight, Is.EqualTo(sp.Appearance.AvatarHeight));
}
}
*/
}

View File

@@ -41,7 +41,6 @@ using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;

View File

@@ -42,7 +42,6 @@ using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;