Refactor and fix #56

This commit is contained in:
Evil Factory
2022-04-15 19:05:24 -03:00
parent 6eb575ea81
commit 42df433d3e
35 changed files with 144 additions and 97 deletions
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Barotrauma
{
public abstract class ACsMod : IDisposable
{
private static List<ACsMod> mods = new List<ACsMod>();
public static List<ACsMod> LoadedMods { get => mods; }
public bool IsDisposed { get; private set; }
public ACsMod()
{
IsDisposed = false;
LoadedMods.Add(this);
Start();
}
public void Dispose() {
Stop();
LoadedMods.Remove(this);
IsDisposed = true;
}
// TODO: some hooks
/// Mod initialization
public abstract void Start();
/// Error or client exit
public abstract void Stop();
}
}
@@ -0,0 +1,79 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
namespace Barotrauma {
class CsScriptFilter
{
private const bool useWhitelist = false;
private static string[] typesPermited = new string[] {
// Basics
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute",
"System.Object",
"System.String",
"System.Collections",
// Some roslyn magic
".DebuggingModes",
// Barotrauma
"Barotrauma",
};
private static string[] typessProhibited = new string[] {
//"System.Reflection",
"System.IO",
};
public static bool IsTypeAllowed(string usingName)
{
if (useWhitelist && !typesPermited.Any(u => u.StartsWith(usingName))) return false;
if (typessProhibited.Any(u => u.StartsWith(usingName))) return false;
return true;
}
public static string FilterSyntaxTree(CSharpSyntaxTree tree)
{
if (tree == null) throw new ArgumentNullException("Syntax tree must not be null.");
{ // Disallow top-level statements
var nodeCheck = tree.GetRoot().DescendantNodes();
var tlStatements = nodeCheck.Where(n => n is GlobalStatementSyntax).ToList();
if (tlStatements.Count > 0)
{
string errStr = "Cmopilation Error:";
foreach (var tls in tlStatements) tls.GetDiagnostics().ToList().ForEach(d => errStr += $"\n {d.ToString()}");
return errStr;
}
}
return null;
}
public static string FilterMetadata(MetadataReader reader)
{
if (reader == null) throw new ArgumentNullException("Metadata Reader must not be null.");
var conflictingTypes = new List<string>();
reader.TypeReferences.ToList().ForEach(t =>
{
var tRef = reader.GetTypeReference(t);
var typeName = $"{reader.GetString(tRef.Namespace)}.{reader.GetString(tRef.Name)}";
if (!IsTypeAllowed(typeName)) conflictingTypes.Add(typeName);
});
if (conflictingTypes.Count > 0)
{
string errStr = "Metadata Error:";
conflictingTypes.ForEach(t => errStr += $"\n Usage of type '{t}' in mods is prohibited.");
return errStr;
}
return null;
}
}
}
@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.CodeAnalysis.Scripting;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq;
using Microsoft.CodeAnalysis;
using System.Runtime.Loader;
using System.Reflection.PortableExecutable;
using System.Reflection.Metadata;
namespace Barotrauma
{
class CsScriptLoader : AssemblyLoadContext
{
public LuaCsSetup setup;
private List<MetadataReference> defaultReferences;
private List<SyntaxTree> syntaxTrees;
public Assembly Assembly { get; private set; }
public CsScriptLoader(LuaCsSetup setup)
{
this.setup = setup;
defaultReferences = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !(a.IsDynamic || string.IsNullOrEmpty(a.Location) || a.Location.Contains("xunit")))
.Select(a => MetadataReference.CreateFromFile(a.Location) as MetadataReference)
.ToList();
syntaxTrees = new List<SyntaxTree>();
Assembly = null;
}
public void SearchFolders()
{
foreach(ContentPackage cp in ContentPackageManager.EnabledPackages.All)
{
var path = Path.GetDirectoryName(cp.Path);
RunFolder(path);
}
}
private void RunFolder(string folder)
{
var scriptFiles = new List<string>();
foreach (var str in DirSearch(folder))
{
var s = str.Replace("\\", "/");
if (s.EndsWith(".cs") && LuaCsFile.IsPathAllowedCsException(s)) scriptFiles.Add(s);
}
try
{
if (scriptFiles.Count <= 0) return;
// Check file content for prohibited stuff
foreach (var file in scriptFiles)
{
var tree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(file), CSharpParseOptions.Default, file);
var error = CsScriptFilter.FilterSyntaxTree(tree as CSharpSyntaxTree);
if (error != null) throw new Exception(error);
syntaxTrees.Add(tree);
}
}
catch (CompilationErrorException ex)
{
string errStr = "Cmopilation Error in '" + folder + "':";
foreach (var diag in ex.Diagnostics)
{
errStr += "\n" + diag.ToString();
}
LuaCsSetup.PrintCsMessage(errStr);
}
catch (Exception ex)
{
LuaCsSetup.PrintCsMessage("Error loading '" + folder + "':\n" + ex.Message + "\n" + ex.StackTrace);
}
}
public List<Type> Compile()
{
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithMetadataImportOptions(MetadataImportOptions.All)
.WithOptimizationLevel(OptimizationLevel.Release)
.WithAllowUnsafe(false);
var compilation = CSharpCompilation.Create("NetScriptAssembly",syntaxTrees, defaultReferences, options);
using (var mem = new MemoryStream())
{
var result = compilation.Emit(mem);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error);
string errStr = "NET MODS NOT LOADED | Mod cmopilation errors:";
foreach (Diagnostic diagnostic in failures)
errStr = $"\n{diagnostic}";
LuaCsSetup.PrintCsMessage(errStr);
}
else
{
mem.Seek(0, SeekOrigin.Begin);
var errStr = CsScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader());
if (errStr == null)
{
mem.Seek(0, SeekOrigin.Begin);
Assembly = LoadFromStream(mem);
}
else LuaCsSetup.PrintCsMessage(errStr);
}
}
syntaxTrees.Clear();
if (Assembly != null)
return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ACsMod))).ToList();
else
throw new Exception("Unable to create net mods assembly.");
}
private static string[] DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.ToArray();
}
}
}