hook merge + hook wrappers

This commit is contained in:
Oiltanker
2022-04-13 01:34:38 +03:00
parent 1e6ac68e86
commit 5d06df437e
40 changed files with 539 additions and 284 deletions
@@ -0,0 +1,41 @@
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 static ACsMod CreateInstance(Type type)
//{
// if (!type.IsSubclassOf(typeof(ACsMod))) throw new Exception("Type argument is not the subclass of ACsMod.");
// return type.GetConstructor(new Type[] { }).Invoke(new object[] { }) as ACsMod;
//}
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();
public virtual void Update() { }
}
}
@@ -0,0 +1,45 @@
using System;
using System.Reflection;
namespace Barotrauma
{
partial class LuaCsSetup
{
// CSharp wrapper for LuaCsHook
public class CsHook : LuaCsHookWrapper
{
public CsHook(LuaCsHook hook) : base(hook) { }
//public enum class HookMethodTypeProxy
//{
// Before = Barotrauma.HookMethodType.Before;
// After = Barotrauma.HookMethodType.After;
// public Barotrauma.HookMethodType type;
// public HookMethodTypeProxy(int i) => type = (Barotrauma.HookMethodType)i;
// public HookMethodTypeProxy(Barotrauma.HookMethodType t) => type = t;
// public static implicit operator Barotrauma.HookMethodType(HookMethodTypeProxy t) => t.type;
// public static implicit operator int(HookMethodTypeProxy t) => (int)t.type;
// public static implicit operator HookMethodTypeProxy(Barotrauma.HookMethodType t) => new HookMethodTypeProxy(t);
// public static implicit operator HookMethodTypeProxy(int i) => new HookMethodTypeProxy(i);
//}
//public readonly HookMethodTypeProxy HookMethodType = new HookMethodTypeProxy(Barotrauma.HookMethodType.Before);
public void HookMethod(string identifier, MethodInfo method, CsPatchDelegate hook, HookMethodType hookType = HookMethodType.Before, ACsMod owner = null) =>
_hook.HookCsMethod(identifier, method, hook, hookType, owner);
public void UnhookMethod(string identifier, MethodInfo method, HookMethodType hookType = HookMethodType.Before) =>
_hook.RemovePatch(identifier, method, hookType);
public void Add(string name, string hookName, CsHookDelegate hook, ACsMod owner = null) =>
_hook.AddCsHook(name, hookName, hook, owner);
}
}
}
@@ -0,0 +1,81 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.IO;
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.File",
};
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,157 @@
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"))
{
LuaCsSetup.PrintCsMessage(s);
scriptFiles.Add(s);
}
}
try
{
if (scriptFiles.Count <= 0) return;
var mainFile = scriptFiles.Find(s => s.EndsWith("Main.cs"));
if (mainFile == null) throw new Exception("Mod folder has no Main.cs file");
scriptFiles.Remove(mainFile);
scriptFiles.Add(mainFile);
// 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();
}
}
}