Skip to content

Commit

Permalink
3.0.37-alpha - dependency updates + wip option to load clrjit
Browse files Browse the repository at this point in the history
e.g. WindowsLaunch.TryFixMonoMod will try and load the net6 platform. This feature will likely be removed if not needed.
  • Loading branch information
SignatureBeef committed Jul 27, 2022
1 parent db4a5a5 commit 6596b5b
Show file tree
Hide file tree
Showing 22 changed files with 189 additions and 143 deletions.
18 changes: 9 additions & 9 deletions OTAPI.Client.Launcher/OTAPI.Client.Launcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@
</ItemGroup> -->
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.87.3" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.ClearScript.linux-x64" Version="7.2.3" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.osx-x64" Version="7.2.3" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.2.3" />
<PackageReference Include="ModFramework" Version="1.0.39-alpha" />
<PackageReference Include="ModFramework.Modules.ClearScript" Version="1.0.39-alpha" GeneratePathProperty="true" />
<PackageReference Include="ModFramework.Modules.CSharp" Version="1.0.39-alpha" GeneratePathProperty="true" />
<PackageReference Include="ModFramework.Modules.Lua" Version="1.0.39-alpha" GeneratePathProperty="true" />
<PackageReference Include="MonoMod.RuntimeDetour.HookGen" Version="22.3.23.4" />
<PackageReference Include="MonoMod" Version="22.3.23.4" />
<PackageReference Include="Microsoft.ClearScript.linux-x64" Version="7.3.1" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.osx-x64" Version="7.3.1" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.3.1" />
<PackageReference Include="ModFramework" Version="1.0.40-alpha" />
<PackageReference Include="ModFramework.Modules.ClearScript" Version="1.0.40-alpha" GeneratePathProperty="true" />
<PackageReference Include="ModFramework.Modules.CSharp" Version="1.0.40-alpha" GeneratePathProperty="true" />
<PackageReference Include="ModFramework.Modules.Lua" Version="1.0.40-alpha" GeneratePathProperty="true" />
<PackageReference Include="MonoMod.RuntimeDetour.HookGen" Version="22.5.1.1" />
<PackageReference Include="MonoMod" Version="22.5.1.1" />
<PackageReference Include="SharpZipLib" Version="1.3.3" />
<PackageReference Include="System.Collections.Specialized" Version="4.3.0" />
<PackageReference Include="System.Drawing.Primitives" Version="4.3.0" />
Expand Down
22 changes: 11 additions & 11 deletions OTAPI.Patcher/OTAPI.Patcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Version>3.0.36-alpha</Version>
<Version>3.0.37-alpha</Version>
<PreserveCompilationContext>true</PreserveCompilationContext>
<PlatformTarget>x64</PlatformTarget>
<RuntimeIdentifiers>win7-x64;osx.10.11-x64;ubuntu.16.04-x64</RuntimeIdentifiers>
Expand All @@ -13,19 +13,19 @@
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>-->
<ItemGroup>
<PackageReference Include="ModFramework" Version="1.0.39-alpha" />
<PackageReference Include="ModFramework.Modules.ClearScript" Version="1.0.39-alpha" />
<PackageReference Include="ModFramework.Modules.CSharp" Version="1.0.39-alpha" />
<PackageReference Include="ModFramework.Modules.Lua" Version="1.0.39-alpha" />
<PackageReference Include="ModFramework" Version="1.0.40-alpha" />
<PackageReference Include="ModFramework.Modules.ClearScript" Version="1.0.40-alpha" />
<PackageReference Include="ModFramework.Modules.CSharp" Version="1.0.40-alpha" />
<PackageReference Include="ModFramework.Modules.Lua" Version="1.0.40-alpha" />
<PackageReference Include="Mono.Cecil" Version="0.11.4" />
<PackageReference Include="MonoMod" Version="22.3.23.4" />
<PackageReference Include="MonoMod.RuntimeDetour.HookGen" Version="22.3.23.4" />
<PackageReference Include="MonoMod" Version="22.5.1.1" />
<PackageReference Include="MonoMod.RuntimeDetour.HookGen" Version="22.5.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Security.Permissions" Version="6.0.0" />
<PackageReference Include="NuGet.Packaging" Version="6.1.0" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.osx-x64" Version="7.2.3" />
<PackageReference Include="Microsoft.ClearScript.linux-x64" Version="7.2.3" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.2.3" />
<PackageReference Include="NuGet.Packaging" Version="6.2.1" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.osx-x64" Version="7.3.1" />
<PackageReference Include="Microsoft.ClearScript.linux-x64" Version="7.3.1" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FNA\FNA.Core.csproj" />
Expand Down
4 changes: 2 additions & 2 deletions OTAPI.Scripts/OTAPI.Scripts.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FNA\FNA.Core.csproj" />
<PackageReference Include="ModFramework" Version="1.0.39-alpha" />
<PackageReference Include="MonoMod" Version="22.3.23.4" />
<PackageReference Include="ModFramework" Version="1.0.40-alpha" />
<PackageReference Include="MonoMod" Version="22.5.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
Expand Down
104 changes: 101 additions & 3 deletions OTAPI.Scripts/Patches/Terraria.WindowsLaunch.Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,119 @@
*/
#pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it

using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

/// <summary>
/// @doc Improves cross platform launch checks
/// @doc Improves cross platform launch checks and add extra launch features
/// </summary>
namespace Terraria
{
class patch_WindowsLaunch
{
public static extern bool orig_SetConsoleCtrlHandler(Terraria.WindowsLaunch.HandlerRoutine handler, bool add);
public static bool SetConsoleCtrlHandler(Terraria.WindowsLaunch.HandlerRoutine handler, bool add)
public static extern bool orig_SetConsoleCtrlHandler(WindowsLaunch.HandlerRoutine handler, bool add);
public static bool SetConsoleCtrlHandler(WindowsLaunch.HandlerRoutine handler, bool add)
{
if (ReLogic.OS.Platform.IsWindows)
{
return orig_SetConsoleCtrlHandler(handler, add);
}
return false;
}

/// <summary>
/// Allows consumers to override the clrjit resolution (if applied)
/// </summary>
public static Func<ProcessModule, string>? OnResolveClrJit;

public static string ResolveClrJitResolution(ProcessModule module)
{
var name = OnResolveClrJit?.Invoke(module);
var res = name ?? module?.FileName ?? "clrjit";

if (VerboseJitInfo)
{
Console.WriteLine("OnResolveClrJit: " + (name ?? "<null>"));
Console.WriteLine("ProcessModule.FileName: " + (module?.FileName ?? "<null>"));
Console.WriteLine("Returned value: " + res);
}

return res;
}

/// <summary>
/// If the MonoMod detour runtime is not .net6 then try and load clrjit and reattach
/// </summary>
public static bool TryResolveClrJit { get; set; }

/// <summary>
/// Enables messages for jit failures
/// </summary>
public static bool VerboseJitInfo { get; set; }

public static void TryFixMonoMod()
{
// MonoMod can fail to find clrjit if Process.Modules does not list it, however NativeLibrary can sometimes find it by name in this scenario
// so this code will rewrite MonoMods discovery to fallback to clrjit by name, allowing it to resolve.
if (DetourHelper.Runtime is not DetourRuntimeNET60Platform)
{
var dn = typeof(DetourRuntimeNETCorePlatform);
var GetJitObject = dn.GetMethod("GetJitObject", BindingFlags.Static | BindingFlags.NonPublic);

if (GetJitObject is not null)
{
var ilh = new ILHook(GetJitObject, il =>
{
var firstEx = il.Instrs
.First(x => x.OpCode == OpCodes.Newobj && x.Operand is MethodReference mref && mref.DeclaringType.Name == "PlatformNotSupportedException")
.Previous
.Previous;
if (firstEx.OpCode != OpCodes.Ldloc_0)
throw new Exception("Method already patched");
if (VerboseJitInfo)
Console.WriteLine("IL location: " + firstEx.OpCode);
while (firstEx.Next.OpCode != OpCodes.Callvirt)
{
if (VerboseJitInfo)
Console.WriteLine("Removing IL: " + firstEx.Next.OpCode);
il.IL.Remove(firstEx.Next);
}
if (VerboseJitInfo)
Console.WriteLine("Updating IL: " + firstEx.Next.OpCode);
firstEx.Next.OpCode = OpCodes.Call;
firstEx.Next.Operand = typeof(WindowsLaunch).GetMethod(nameof(ResolveClrJitResolution));
});

DetourHelper.Runtime = DetourRuntimeNETCorePlatform.Create();
}

if (VerboseJitInfo && DetourHelper.Runtime is not DetourRuntimeNET60Platform)
Console.WriteLine("Failed to resolve clrjit, you might experience hook failures.");
}
}

public static extern void orig_Main(string[] args);
public static void Main(string[] args)
{
if (TryResolveClrJit)
TryFixMonoMod();

if (VerboseJitInfo)
Console.WriteLine("MonoMod Runtime: " + (DetourHelper.Runtime.GetType().FullName ?? "<null>"));

orig_Main(args);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,8 @@ void ClientGetDataExceptions(ModFramework.ModFwModder modder)
csr.Goto(handler.HandlerEnd.Previous(x => x.OpCode == OpCodes.Leave_S), MonoMod.Cil.MoveType.Before);

csr.Emit(OpCodes.Ldloc, exVariable);
csr.EmitDelegate<CheckBytesExceptionCallback>(OTAPI.Hooks.NetMessage.InvokeCheckBytesException);
csr.EmitDelegate(OTAPI.Hooks.NetMessage.InvokeCheckBytesException);
}


[MonoMod.MonoModIgnore]
public delegate void CheckBytesExceptionCallback(Exception exception);

namespace OTAPI
{
Expand Down
6 changes: 1 addition & 5 deletions OTAPI.Scripts/TopLevelScripts/HookClientGetData.Both.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,11 @@ void HookClientGetData(MonoModder modder)
GetData.Emit(prm.IsOut ? OpCodes.Ldarg : OpCodes.Ldarga, prm);

GetData.Emit(OpCodes.Ldc_I4, maxPackets);
GetData.EmitDelegate<GetDataCallback>(OTAPI.Hooks.MessageBuffer.InvokeGetData);
GetData.EmitDelegate(OTAPI.Hooks.MessageBuffer.InvokeGetData);
GetData.Emit(OpCodes.Brtrue, GetData.Instrs[GetData.Index]);
GetData.Emit(OpCodes.Ret);
}

// this is merely the callback signature
[MonoMod.MonoModIgnore]
public delegate bool GetDataCallback(global::Terraria.MessageBuffer instance, ref byte packetId, ref int readOffset, ref int start, ref int length, ref int messageType, int maxPackets);

namespace OTAPI
{
public static partial class Hooks
Expand Down
5 changes: 1 addition & 4 deletions OTAPI.Scripts/TopLevelScripts/HookClientSendBytes.Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,12 @@ void HookClientSendBytes(MonoModder modder)
if (handler.TryStart.Next.OpCode == OpCodes.Ldloc_S || handler.TryStart.Next.OpCode == OpCodes.Ldarg_1)
{
SendData.Emit(handler.TryStart.Next.OpCode, handler.TryStart.Next.Operand);
SendData.EmitDelegate<SendBytesCallback>(OTAPI.Hooks.NetMessage.InvokeSendBytes);
SendData.EmitDelegate(OTAPI.Hooks.NetMessage.InvokeSendBytes);
SendData.Remove();
}
}
}

[MonoMod.MonoModIgnore]
public delegate void SendBytesCallback(Terraria.Net.Sockets.ISocket socket, byte[] data, int offset, int size, global::Terraria.Net.Sockets.SocketSendCallback callback, object state, int remoteClient);

namespace OTAPI
{
public static partial class Hooks
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,11 @@ void HardModeTileUpdates(MonoModder modder)

csr.Emit(csrTypes[0].Next.OpCode, csrTypes[0].Next.Operand);

csr.EmitDelegate<HardmodeTilePlaceCallback>(OTAPI.Hooks.WorldGen.InvokeHardmodeTileUpdate);
csr.EmitDelegate(OTAPI.Hooks.WorldGen.InvokeHardmodeTileUpdate);
csr.Emit(OpCodes.Brfalse_S, continueBranch);
}
}

[MonoMod.MonoModIgnore]
public delegate bool HardmodeTilePlaceCallback(int x, int y, ushort type);

namespace OTAPI
{
public static partial class Hooks
Expand Down
6 changes: 1 addition & 5 deletions OTAPI.Scripts/TopLevelScripts/HookMainStatusText.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,9 @@ void HookMainStatusText(MonoModder modder, IRelinkProvider relinkProvider)
var csr = modder.GetILCursor(property.SetMethod);
csr.GotoNext(MonoMod.Cil.MoveType.Before, i => i.Operand is FieldReference fr && fr.Name.Contains("__BackingField"));

csr.EmitDelegate<OnStatusTextChangeCallback>(OTAPI.Hooks.Main.InvokeStatusTextChange);
csr.EmitDelegate(OTAPI.Hooks.Main.InvokeStatusTextChange);
}


[MonoMod.MonoModIgnore]
public delegate string OnStatusTextChangeCallback(string value);

namespace OTAPI
{
public static partial class Hooks
Expand Down
77 changes: 29 additions & 48 deletions OTAPI.Scripts/TopLevelScripts/HookMechSpawn.Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,57 +34,38 @@
[MonoModIgnore]
void HookMechSpawn(MonoModder modder)
{
foreach (var task in new[]
{
new Task()
{
Method = () => Terraria.NPC.MechSpawn(0,0,0),
Callback = OTAPI.Hooks.NPC.InvokeMechSpawn,
},
new Task()
{
Method = () => Terraria.Item.MechSpawn(0, 0, 0),
Callback = OTAPI.Hooks.Item.InvokeMechSpawn,
},
})
{
var csr = modder.GetILCursor(task.Method);

//while (csr.TryFindNext(out ILCursor[] matches, ins => ins.OpCode == OpCodes.Ret))
var matches = csr.Body.Instructions.Where(x => x.OpCode == OpCodes.Ret).ToArray();
{
foreach (var ret in matches)
{
csr.Goto(ret, MoveType.Before);

// add the method params to the stack.
foreach (var prm in csr.Method.Parameters)
csr.Emit(OpCodes.Ldarg, prm);

var www = csr.Body.Variables.Where(x => x.VariableType == csr.Module.TypeSystem.Int32).Take(3);
if (www.Count() != 3)
throw new Exception($"{csr.Method.FullName} was expected to contain 3 integer variables.");

foreach (var lv in www)
csr.Emit(OpCodes.Ldloc, lv);

csr.EmitDelegate(task.Callback);
}
}
}
}

HookMethod(modder, () => Terraria.NPC.MechSpawn(0, 0, 0), OTAPI.Hooks.NPC.InvokeMechSpawn);
HookMethod(modder, () => Terraria.Item.MechSpawn(0, 0, 0), OTAPI.Hooks.Item.InvokeMechSpawn);
}

[MonoModIgnore]
class Task
{
public Expression<Action> Method { get; set; }
public MechSpawnCallback Callback { get; set; }
void HookMethod(MonoModder modder, Expression<Action> method, Func<bool, float, float, int, int, int, int, bool> Callback)
{
var csr = modder.GetILCursor(method);

//while (csr.TryFindNext(out ILCursor[] matches, ins => ins.OpCode == OpCodes.Ret))
var matches = csr.Body.Instructions.Where(x => x.OpCode == OpCodes.Ret).ToArray();
{
foreach (var ret in matches)
{
csr.Goto(ret, MoveType.Before);

// add the method params to the stack.
foreach (var prm in csr.Method.Parameters)
csr.Emit(OpCodes.Ldarg, prm);

var www = csr.Body.Variables.Where(x => x.VariableType == csr.Module.TypeSystem.Int32).Take(3);
if (www.Count() != 3)
throw new Exception($"{csr.Method.FullName} was expected to contain 3 integer variables.");

foreach (var lv in www)
csr.Emit(OpCodes.Ldloc, lv);

csr.EmitDelegate(Callback);
}
}
}

// this is merely the callback signature
[MonoMod.MonoModIgnore]
public delegate bool MechSpawnCallback(bool result, float x, float y, int type, int num, int num2, int num3);

namespace OTAPI
{
public static partial class Hooks
Expand Down
7 changes: 2 additions & 5 deletions OTAPI.Scripts/TopLevelScripts/HookMeteors.Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ void HookMeteors(ModFramework.ModFwModder modder)
new { OpCodes.Ldarga, Operand = csr.Method.Parameters[1] } //reference to int y
);

csr.EmitDelegate<MeteorCallback>(OTAPI.Hooks.WorldGen.InvokeMeteor);
csr.EmitDelegate(OTAPI.Hooks.WorldGen.InvokeMeteor);

csr.EmitAll(
//If the callback is not canceled, continue on with vanilla code
Expand All @@ -65,10 +65,7 @@ void HookMeteors(ModFramework.ModFwModder modder)
new { OpCodes.Ldc_I4_0 }, //false
new { OpCodes.Ret } //return
);
}

[MonoMod.MonoModIgnore]
public delegate bool MeteorCallback(ref int x, ref int y);
}

namespace OTAPI
{
Expand Down
3 changes: 0 additions & 3 deletions OTAPI.Scripts/TopLevelScripts/HookNpcCreate.Both.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,6 @@ void HookNpcCreate(MonoModder modder)
NewNPC.Emit(OpCodes.Ldarg, prm);
}

[MonoMod.MonoModIgnore]
public delegate Terraria.NPC NpcCreateCallback();

namespace OTAPI
{
public static partial class Hooks
Expand Down

0 comments on commit 6596b5b

Please sign in to comment.