Using a `bool` inside a struct, breaks `out`/`ref` parameters with IL2CPP
Unity Version: Unity 2022.3.20f1 (IL2CPP) BepInEx Version: BepInEx 6.0.0-be.733
Using the following Unity Code:
public struct EnsoRecordInfo
{
public bool allGood;
public int ensoGamePlayCount;
public int playCount;
public int trainingPlayCount;
}
public class reftest : MonoBehaviour
{
static EnsoRecordInfo[] ensoRecords = new EnsoRecordInfo[40];
[MethodImpl(MethodImplOptions.NoInlining)]
public unsafe static bool GetNormalRecordInfo(int playerNo, int songUid, out EnsoRecordInfo dst)
{
fixed(EnsoRecordInfo* ensoPointer = &dst)
Debug.Log($"Original GetNormalRecordInfo:{((long)ensoPointer).ToString("x")}");
dst = new EnsoRecordInfo();
dst.ensoGamePlayCount = 20;
return true;
}
unsafe void Update()
{
fixed(EnsoRecordInfo* ensoPointer = &ensoRecords[20])
Debug.Log($"Original Update:{((long)ensoPointer).ToString("x")}");
var result = GetNormalRecordInfo(3, 2, out ensoRecords[20]);
Debug.Log($"EnsoGamePlayCount:{ensoRecords[20].ensoGamePlayCount}");
}
}
With the following patch:
[HarmonyPostfix]
[HarmonyPatch(typeof(reftest), nameof(reftest.GetNormalRecordInfo))]
[HarmonyPatch(
new Type[] {typeof(int), typeof(int), typeof(EnsoRecordInfo)},
new ArgumentType[] { ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out }
)]
public unsafe static void getnormalRecord_PostFix(ref EnsoRecordInfo dst)
{
fixed (EnsoRecordInfo* ensoPointer = &dst)
Logger.Log($"Modded GetNormalRecordInfo:{((long)ensoPointer).ToString("x")}");
dst = new EnsoRecordInfo();
dst.ensoGamePlayCount = 40;
}
Produces the following log:
[Message: Unity] Original Update:1740c07dde0
[Message: Unity] Original GetNormalRecordInfo:524ef5e9f8
[Info :ModTemplate] Modded GetNormalRecordInfo:524ef5e9f8
[Message: Unity] EnsoGamePlayCount:0
Where as without any patches, this is the log:
[Message: Unity] Original Update:2538e41dde0
[Message: Unity] Original GetNormalRecordInfo:2538e41dde0
[Message: Unity] EnsoGamePlayCount:20
Notice how EnsoGamePlayCount its 0, not even 20, and the address changes after patching the function.
This behavior starts when adding a bool to EnsoGamePlayCount, and it happens even if the patch function its completly empty.
By removing the allGood member, EnsoGamePlayCount its set to be 40 at the end of Update as expected, but the address still changes, so I'm guessing that's normal behavior? If it is, i wonder what happens in cases like this, where you pass a element of an array as a ref/out parameter, could it be that the new address points to another element of the array, leading to undefined behavior?
This was done on a recreation, but this problem happened to me on Taiko no Tatsujin: Rhythm Festival with the almost equivalent function MusicDataUtility.GetNormalRecordInfo