initial cs-lua merge work

This commit is contained in:
Oiltanker
2022-04-11 22:44:53 +03:00
parent ae2b84cceb
commit 1e6ac68e86
44 changed files with 786 additions and 1046 deletions
@@ -1,255 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using MoonSharp.Interpreter;
using HarmonyLib;
using System.Collections.Generic;
using System.Text;
namespace Barotrauma
{
using NetHookMethod = Func<object[], object>;
using HookMethod = Func<object, Dictionary<string, object>, object>;
partial class NetHook
{
public NetHook()
{
_hookPrefixMethods = new Dictionary<long, HashSet<Tuple<string, HookMethod>>>();
_hookPostfixMethods = new Dictionary<long, HashSet<Tuple<string, HookMethod>>>();
}
private Dictionary<string, List<NetHookMethod>> hookFunctions = new Dictionary<string, List<NetHookMethod>>();
private static Dictionary<long, HashSet<Tuple<string, HookMethod>>> _hookPrefixMethods;
private static Dictionary<long, HashSet<Tuple<string, HookMethod>>> _hookPostfixMethods;
private Queue<Tuple<float, NetHookMethod, object[]>> queuedFunctionCalls = new Queue<Tuple<float, NetHookMethod, object[]>>();
public enum HookMethodType
{
Before, After
}
static void _hookNetPatch(MethodBase __originalMethod, object[] __args, object __instance, out object result, HookMethodType hookMethodType)
{
result = null;
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return;
#endif
try
{
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<Tuple<string, HookMethod>> methodSet = null;
switch (hookMethodType)
{
case HookMethodType.Before:
_hookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break;
case HookMethodType.After:
_hookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break;
default:
break;
}
if (methodSet != null)
{
var @params = __originalMethod.GetParameters();
var ptable = new Dictionary<string, object>();
for (int i = 0; i < @params.Length; i++)
{
ptable.Add(@params[i].Name, __args[i]);
}
foreach (var tuple in methodSet)
{
result = tuple.Item2(__instance, ptable);
}
}
}
catch (Exception ex)
{
GameMain.Net.HandleException(ex, null);
}
}
private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
public void HookMethod(string identifier, MethodInfo methodInfo, HookMethod hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
if (identifier == null || methodInfo == null || methodInfo == null) throw new ArgumentNullException("All 'HookMethod' arguments must not be null.");
identifier = identifier.ToLower();
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method));
}
}
if (_hookPrefixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, HookMethod>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPrefixMethods.Add(funcAddr, new HashSet<Tuple<string, HookMethod>>() { Tuple.Create(identifier, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method));
}
}
if (_hookPostfixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, HookMethod>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPostfixMethods.Add(funcAddr, new HashSet<Tuple<string, HookMethod>>() { Tuple.Create(identifier, hookMethod) });
}
}
}
public void EnqueueFunction(NetHookMethod function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, NetHookMethod, object[]>(0, function, args));
}
public void EnqueueTimedFunction(float time, NetHookMethod function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, NetHookMethod, object[]>(time, function, args));
}
public void Add(string name, NetHookMethod hook)
{
if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null");
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
hookFunctions.Add(name, new List<NetHookMethod>());
hookFunctions[name].Add(hook);
}
public void Remove(string name, NetHookMethod hook)
{
if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null");
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return;
if (hookFunctions[name].Contains(hook))
hookFunctions[name].Remove(hook);
}
public void Update()
{
try
{
if (queuedFunctionCalls.TryPeek(out Tuple<float, NetHookMethod, object[]> result))
{
if (Timing.TotalTime >= result.Item1)
{
result.Item2(result.Item3);
queuedFunctionCalls.Dequeue();
}
}
}
catch (Exception ex)
{
GameMain.Net.HandleException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}");
}
}
public object Call(string name, params object[] args)
{
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return null;
#endif
if (GameMain.Net == null) return null;
if (name == null) return null;
if (args == null) { args = new object[] { }; }
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return null;
object lastResult = null;
foreach (var hook in hookFunctions[name])
{
try
{
var result = hook(args);
if (!(result == null))
lastResult = result;
}
catch (Exception e)
{
StringBuilder argsSb = new StringBuilder();
foreach (var arg in args)
{
argsSb.Append(arg + " ");
}
GameMain.Net.HandleException(e, $"Error in Hook '{name}'->'{hook}', with args '{argsSb}'\n{Environment.StackTrace}");
}
}
return lastResult;
}
}
}
@@ -13,150 +13,147 @@ using static NetScript;
namespace Barotrauma
{
partial class NetSetup
class NetScriptLoader : AssemblyLoadContext
{
public LuaCsSetup setup;
private List<MetadataReference> defaultReferences;
private List<SyntaxTree> syntaxTrees;
public Assembly Assembly { get; private set; }
public class NetScriptLoader : AssemblyLoadContext
public NetScriptLoader(LuaCsSetup setup)
{
public NetSetup net;
private List<MetadataReference> defaultReferences;
private List<SyntaxTree> syntaxTrees;
public Assembly Assembly { get; private set; }
this.setup = setup;
public NetScriptLoader(NetSetup net)
{
this.net = net;
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 GameMain.Config.AllEnabledPackages)
{
var path = Path.GetDirectoryName(cp.Path);
RunFolder(path);
}
}
public void RunFolder(string folder)
{
var scriptFiles = new List<string>();
foreach (var str in DirSearch(folder))
{
var s = str.Replace("\\", "/");
if (s.EndsWith(".cs"))
{
NetSetup.PrintMessage(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 = NetScriptFilter.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();
}
NetSetup.PrintMessage(errStr);
}
catch (Exception ex)
{
NetSetup.PrintMessage("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}";
NetSetup.PrintMessage(errStr);
}
else
{
mem.Seek(0, SeekOrigin.Begin);
var errStr = NetScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader());
if (errStr == null)
{
mem.Seek(0, SeekOrigin.Begin);
Assembly = LoadFromStream(mem);
}
else NetSetup.PrintMessage(errStr);
}
}
syntaxTrees.Clear();
if (Assembly != null)
return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ANetMod))).ToList();
else
throw new Exception("Unable to create net mods assembly.");
}
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();
}
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 = NetScriptFilter.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 = NetScriptFilter.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(ANetMod))).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();
}
}
}
@@ -1,102 +0,0 @@
using System;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using HarmonyLib;
using System.Runtime.CompilerServices;
//using System.Linq;
//using System.Collections.Generic;
//using Microsoft.CodeAnalysis;
//using Microsoft.CodeAnalysis.CSharp;
[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)]
namespace Barotrauma
{
partial class NetSetup : IDisposable
{
public NetScriptLoader Loader { get; private set; }
public Harmony harmony;
public LuaHook hook;
public NetSetup() => Initialize();
public void Dispose() => Stop();
public void Reload()
{
Stop();
Initialize();
Execute();
}
public void Initialize()
{
hook = new LuaHook();
Loader = new NetScriptLoader(this);
Loader.SearchFolders();
}
public void Execute()
{
if (Loader == null) throw new Exception("NetSetup was not properly initialized.");
try
{
var modTypes = Loader.Compile();
modTypes.ForEach(t => t.GetConstructor(new Type[] { }).Invoke(null));
}
catch (Exception ex)
{
PrintMessage(ex);
}
}
public void Stop()
{
ANetMod.LoadedMods.ForEach(m => m.Dispose());
ANetMod.LoadedMods.Clear();
Loader.Unload();
harmony?.UnpatchAll();
hook?.Call("stop", new object[] { });
hook = null;
Loader = null;
}
public void Update()
{
hook?.Update();
ANetMod.LoadedMods.ForEach(m => m.Update());
}
public static void PrintMessage(object message)
{
if (message == null) { message = "null"; }
string str = message.ToString();
#if SERVER
if (GameMain.Server != null)
{
for (int i = 0; i < str.Length; i += 1024)
{
string subStr = str.Substring(i, Math.Min(1024, str.Length - i));
foreach (var c in GameMain.Server.ConnectedClients)
{
GameMain.Server.SendDirectChatMessage(ChatMessage.Create("", subStr, ChatMessageType.Console, null, textColor: Color.MediumPurple), c);
}
GameServer.Log("[NET] " + subStr, ServerLog.MessageType.ServerMessage);
}
}
else
{
DebugConsole.NewMessage("[NET]" + message.ToString(), Color.MediumPurple);
}
#else
DebugConsole.NewMessage(message.ToString(), Color.Purple);
#endif
}
public void HandleException(Exception ex, string? info)
{
throw new NotImplementedException();
}
}
}