Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
using HarmonyLib;
using System;
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;

// ReSharper disable InconsistentNaming
// ReSharper disable PossibleMultipleEnumeration

namespace RustServerMetrics.HarmonyPatches;

[HarmonyPatch(typeof(BasePlayer), nameof(BasePlayer.OnDisconnected))]
public class BasePlayer_OnDisconnected_Patch
{
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> originalInstructions)
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var retList = new List<CodeInstruction>(originalInstructions);
try
{
var matcher = new CodeMatcher(instructions)
.Start()
.InsertAndAdvance(
new CodeInstruction(
OpCodes.Ldsfld,
AccessTools.Field(
typeof(SingletonComponent<MetricsLogger>),
nameof(SingletonComponent<MetricsLogger>.Instance))),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(
OpCodes.Call,
AccessTools.Method(
typeof(MetricsLogger),
nameof(MetricsLogger.OnPlayerDisconnected))));

var fieldInfo = typeof(SingletonComponent<MetricsLogger>)
.GetField(nameof(SingletonComponent<MetricsLogger>.Instance), BindingFlags.Static | BindingFlags.Public);

var methodInfo = typeof(MetricsLogger)
.GetMethod(nameof(MetricsLogger.OnPlayerDisconnected), BindingFlags.Instance | BindingFlags.NonPublic);

retList.InsertRange(0, [
new CodeInstruction(OpCodes.Ldsfld, fieldInfo),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call, methodInfo)
]);

return retList;
return matcher.Instructions();
}
catch (Exception e)
{
Debug.LogError($"[ServerMetrics] {nameof(BasePlayer_OnDisconnected_Patch)}: " + e.Message);
return instructions;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,56 +1,53 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;

// ReSharper disable InconsistentNaming
// ReSharper disable PossibleMultipleEnumeration

namespace RustServerMetrics.HarmonyPatches;

[HarmonyPatch(typeof(BasePlayer), nameof(BasePlayer.PerformanceReport))]
public class BasePlayer_PerformanceReport_Patch
{
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> originalInstructions,
ILGenerator ilGenerator)
public static IEnumerable<CodeInstruction> Transpiler(
IEnumerable<CodeInstruction> instructions,
ILGenerator ilGenerator)
{
var instructionsList = originalInstructions.ToList();
var jumpLabel = ilGenerator.DefineLabel();

CodeMatch[] needle =
[
new(OpCodes.Ldloc_0),
new(OpCodes.Ldstr, "legacy"),
new(OpCodes.Call, AccessTools.Method(typeof(String), "op_Equality")),
new(OpCodes.Brfalse)
];

CodeInstruction[] injection =
[
new(OpCodes.Ldsfld, AccessTools.Field(typeof(SingletonComponent<MetricsLogger>), nameof(SingletonComponent<MetricsLogger>.Instance))),
new(OpCodes.Ldloc_1),
new(OpCodes.Call, AccessTools.Method(typeof(MetricsLogger), nameof(MetricsLogger.OnClientPerformanceReport))),
new(OpCodes.Brtrue, jumpLabel)
];

try
{
var codeMatcher = new CodeMatcher(instructionsList);

codeMatcher.MatchEndForward(needle)
.ThrowIfInvalid("Unable to find the expected injection point")
.Advance(1)
.InsertAndAdvance(injection)
.End()
.AddLabels([jumpLabel]);
var matcher = new CodeMatcher(instructions, ilGenerator)
.End()
.CreateLabel(out var retLabel)
.MatchEndBackwards(
new CodeMatch(OpCodes.Ldloc_0),
new CodeMatch(OpCodes.Ldstr, "legacy"),
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(string), "op_Equality")),
new CodeMatch(OpCodes.Brfalse))
.ThrowIfInvalid("Unable to find the expected injection point")
.Advance(1)
.InsertAndAdvance(
new CodeInstruction(
OpCodes.Ldsfld,
AccessTools.Field(
typeof(SingletonComponent<MetricsLogger>),
nameof(SingletonComponent<MetricsLogger>.Instance))),
new CodeInstruction(OpCodes.Ldloc_1),
new CodeInstruction(
OpCodes.Call,
AccessTools.Method(
typeof(MetricsLogger),
nameof(MetricsLogger.OnClientPerformanceReport))),
new CodeInstruction(OpCodes.Brtrue, retLabel));

return codeMatcher.Instructions();
return matcher.Instructions();
}
catch (Exception e)
{
UnityEngine.Debug.LogError($"[ServerMetrics] {nameof(BasePlayer_PerformanceReport_Patch)}: " + e.Message);
return instructionsList;
return instructions;
}
}
}
59 changes: 36 additions & 23 deletions src/RustServerMetrics/HarmonyPatches/BasePlayer_PlayerInit_Patch.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,50 @@
using HarmonyLib;
using System;
using System;
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;

// ReSharper disable InconsistentNaming
// ReSharper disable PossibleMultipleEnumeration

namespace RustServerMetrics.HarmonyPatches;

[HarmonyPatch(typeof(BasePlayer), nameof(BasePlayer.PlayerInit))]
public class BasePlayer_PlayerInit_Patch
{
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> originalInstructions)
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var retList = new List<CodeInstruction>(originalInstructions);

var fieldInfo = typeof(SingletonComponent<MetricsLogger>)
.GetField(nameof(SingletonComponent<MetricsLogger>.Instance), BindingFlags.Static | BindingFlags.Public);

var methodInfo = typeof(MetricsLogger)
.GetMethod(nameof(MetricsLogger.OnPlayerInit), BindingFlags.Instance | BindingFlags.NonPublic);

var idx = retList.FindIndex(x => x.opcode == OpCodes.Call && x.operand is MethodInfo methodInfo1 && methodInfo1.DeclaringType.Name == "EACServer" && methodInfo1.Name == "OnStartLoading");

if (idx < 0) throw new Exception("Failed to find the insertion index for PlayerInit");

retList.InsertRange(idx, [
new CodeInstruction(OpCodes.Ldsfld, fieldInfo),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call, methodInfo)
]);

return retList;
try
{
var matcher = new CodeMatcher(instructions)
.MatchEndForward(
new CodeMatch(
OpCodes.Call,
AccessTools.Method(
typeof(EACServer),
nameof(EACServer.OnStartLoading))))
.ThrowIfInvalid("Failed to find insertion point for BasePlayer.PlayerInit")
.Advance(1)
.InsertAndAdvance(
new CodeInstruction(
OpCodes.Ldsfld,
AccessTools.Field(
typeof(SingletonComponent<MetricsLogger>),
nameof(SingletonComponent<MetricsLogger>.Instance))),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(
OpCodes.Call,
AccessTools.Method(
typeof(MetricsLogger),
nameof(MetricsLogger.OnPlayerInit))));

return matcher.Instructions();
}
catch (Exception e)
{
Debug.LogError($"[ServerMetrics] {nameof(BasePlayer_PlayerInit_Patch)}: " + e.Message);
return instructions;
}
}
}
34 changes: 22 additions & 12 deletions src/RustServerMetrics/HarmonyPatches/Bootstrap_StartServer_Patch.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
using HarmonyLib;
using System;
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;

// ReSharper disable InconsistentNaming
// ReSharper disable PossibleMultipleEnumeration

namespace RustServerMetrics.HarmonyPatches;

[HarmonyPatch(typeof(Bootstrap), nameof(Bootstrap.StartServer))]
public class Bootstrap_StartServer_Patch
{
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> originalInstructions)
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var retList = new List<CodeInstruction>(originalInstructions);
try
{
var matcher = new CodeMatcher(instructions)
.Start()
.InsertAndAdvance(
new CodeInstruction(
OpCodes.Call,
AccessTools.Method(
typeof(MetricsLogger),
nameof(MetricsLogger.Initialize))));

var methodInfo = typeof(MetricsLogger)
.GetMethod(nameof(MetricsLogger.Initialize), BindingFlags.Static | BindingFlags.NonPublic);

retList.InsertRange(0, [
new CodeInstruction(OpCodes.Call, methodInfo)
]);

return retList;
return matcher.Instructions();
}
catch (Exception e)
{
Debug.LogError($"[ServerMetrics] {nameof(Bootstrap_StartServer_Patch)}: " + e.Message);
return instructions;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ internal class ConsoleSystem_Internal_Patch
[HarmonyPrepare]
public static bool Prepare()
{
if (!RustServerMetricsLoader.__serverStarted)
if (RustServerMetricsLoader.__serverStarted)
{
Debug.Log("Note: Cannot patch ConsoleSystem_Internal_Patch yet. We will patch it upon server start.");
return false;
return true;
}

return true;

Debug.Log($"[ServerMetrics] Note: Cannot patch {nameof(ConsoleSystem_Internal_Patch)} yet. We will patch it upon server start.");
return false;
}

[HarmonyTargetMethods]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;

// ReSharper disable once InconsistentNaming
// ReSharper disable PossibleMultipleEnumeration

namespace RustServerMetrics.HarmonyPatches.Delayed;

Expand All @@ -19,60 +19,60 @@ internal static class InvokeHandlerBase_DoTick_Patch

private static readonly double TicksToMs = 1000.0 / Stopwatch.Frequency;

private static readonly CodeMatch[] NeedleSequenceToFind =
[
CodeMatch.LoadsField(AccessTools.Field(typeof(InvokeAction), nameof(InvokeAction.action))),
CodeMatch.Calls(AccessTools.Method(typeof(Action), nameof(Action.Invoke)))
];

private static readonly CodeInstruction[] SequenceToInject =
[
new(OpCodes.Call, AccessTools.Method(typeof(InvokeHandlerBase_DoTick_Patch), nameof(InvokeWrapper)))
];

#endregion

#region Patching

[HarmonyPrepare]
public static bool Prepare()
{
// ReSharper disable once InvertIf
if (!RustServerMetricsLoader.__serverStarted)
if (RustServerMetricsLoader.__serverStarted)
{
UnityEngine.Debug.Log("Note: Cannot patch InvokeHandlerBase_DoTick_Patch yet. We will patch it upon server start.");
return false;
return true;
}

return true;
UnityEngine.Debug.Log($"[ServerMetrics] Note: Cannot patch {nameof(InvokeHandlerBase_DoTick_Patch)} yet. We will patch it upon server start.");
return false;
}

[HarmonyTargetMethods]
public static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.DeclaredMethod(typeof(InvokeHandlerBase<InvokeHandler>), nameof(InvokeHandlerBase<InvokeHandler>.DoTick));
yield return AccessTools.DeclaredMethod(
typeof(InvokeHandlerBase<InvokeHandler>),
nameof(InvokeHandlerBase<InvokeHandler>.DoTick));
}

[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> originalInstructions)
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var instructionsList = originalInstructions.ToList();

try
{
var codeMatcher = new CodeMatcher(instructionsList);

codeMatcher.MatchStartForward(NeedleSequenceToFind)
.ThrowIfInvalid("Unable to find the expected injection point")
.RemoveInstructions(2)
.InsertAndAdvance(SequenceToInject);
var codeMatcher = new CodeMatcher(instructions)
.MatchStartForward(
CodeMatch.LoadsField(
AccessTools.Field(
typeof(InvokeAction),
nameof(InvokeAction.action))),
CodeMatch.Calls(
AccessTools.Method(
typeof(Action),
nameof(Action.Invoke))))
.ThrowIfInvalid("Unable to find the expected injection point")
.RemoveInstructions(2)
.InsertAndAdvance(
new CodeInstruction(
OpCodes.Call,
AccessTools.Method(
typeof(InvokeHandlerBase_DoTick_Patch),
nameof(InvokeWrapper))));

return codeMatcher.Instructions();
}
catch (Exception e)
{
UnityEngine.Debug.LogError($"[ServerMetrics] {nameof(InvokeHandlerBase_DoTick_Patch)}: " + e.Message);
return instructionsList;
return instructions;
}
}

Expand Down
Loading